Create new Folder with Formidable - node.js

I have the next code:
router.post('/subirArchivo', function (req, res){
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file){
file.path = path.join(__dirname,'../../../../uploads/', file.name);
});
form.on('file', function (name, file){
console.log('Uploaded ' + file.name);
});
res.sendFile(path.join(__dirname,'../../../client/views/faseVinculacion', 'busquedaVinculacion.html'))
Upload the file it's fine, but, how create a new folder that not exists?

First you need to add fs-extra (easier way)
and in your post, add:
fs.mkdirsSync(__dirname + '/../public/dist');
form.uploadDir = __dirname + '/../public/dist';
more details:
if (req.url == '/upload') {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
fs.mkdirsSync(__dirname + '/../public/dist');
form.uploadDir = __dirname + '/../public/dist';
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);
}

Related

multiple file upload not working with formidable in node js

app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
try{
if (files.file.name != '') {
file_newname = dt.MD5(files.file.name + Date() + Math.random()) + '.jpg' + ;
var file_newpath = './tmp/' + file_newname;
fs.readFile(file_oldpath, function (err, data) {
// Write the file
fs.writeFile(file_newpath, data, function (err) {
console.log('File written!');
res.end(JSON.stringify({
message: 'file uploaded successfully'
}));
});
});
}
}catch (e) {
}
});
});
The single image upload is working perfectly.I tried the following code
var form = new formidable.IncomingForm();
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);
But only a single image gets uploaded. i m using react in frontend. Node and express in backend.
I also tried multer. But that doesnt working
app.post('/getrast', upload.array('files'), function (req, res) {
res.json({data: req.files});
});
Use the multiple flag with the incoming form with true as value.
var form = new formidable.IncomingForm();
form.multiples = true; //use this while dealing with multiple files
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
fs.rename('add your logic here for renaming files'); // rename it here
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);

formidable saves file without extension in Node js

app.post('/file_upload', function (req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/uploads');
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
// res.redirect('/forms');
});
form.parse(req);
});
UI used to upload multiple images in nodejs using formidable
The files are being creating. But the images are getting saved without extension.
Is there anything extra steps i have to do?
This worked for me:
form.keepExtensions = true;
Try onPart:
form.on('part', function (part) {
if (part.filename) {
if (!isInvalidFileName(part.filename) || !isInvalidMimeType(part.mime)) {
files.push([part]);
}
}
})

I want to get a callback function's variable another function

coin.js
app.post('/upload', upload.single('userfile'), function(req, res){
var filename = __dirname +'/'+ req.file.path;
var s = fs.ReadStream(filename);
s.on('data', function(data) {
shasum.update(data)
})
s.on('end', function() {
var hash = shasum.digest('hex') //this var
console.log("Hash : "+ hash + ' ' + filename)
fs.unlink(filename, function (err) { //파일제거
if (err) throw err;
console.log('successfully deleted '+ filename); });
res.send('Uploaded : ' + hash + " " + filename);
})
})
app.get('/stampid', function(req, res){
client.stampDocument(hash, function(err, stampId) { //i want to call hash
res.render('coin2', {si:stampId})
});
})
I have a this code, then I want to call a var 'hash' in the function below.
I don't know what to do, I want fixed code.
I need your help.
use global variable :
var hash; // <----- declare it here
app.post('/upload', upload.single('userfile'), function(req, res){
var filename = __dirname +'/'+ req.file.path;
var s = fs.ReadStream(filename);
s.on('data', function(data) {
shasum.update(data)
})
s.on('end', function() {
hash = shasum.digest('hex') //this var
console.log("Hash : "+ hash + ' ' + filename)
fs.unlink(filename, function (err) { //파일제거
if (err) throw err;
console.log('successfully deleted '+ filename); });
res.send('Uploaded : ' + hash + " " + filename);
})
})
app.get('/stampid', function(req, res){
client.stampDocument(hash, function(err, stampId) { //i want to call hash
res.render('coin2', {si:stampId})
});
})

How to view image in img tag

I got problem that i cant get this code to save to image in a img tag. the picture will only show the first time i enter the site, the next time i enter the site it is gone. guess its the pipe but is there a way to keep it there? have searched for days now...
this is my code to save it and get it.
router.post('/', function(req, res, next) {
var busboy = new Busboy({ headers : req.headers });
var fileId = new mongo.ObjectId();
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('got file', filename, mimetype, encoding);
var writeStream = gfs.createWriteStream({
_id: fileId,
filename: filename,
mode: 'w',
content_type: mimetype,
});
file.pipe(writeStream);
}).on('finish', function() {
// show a link to the uploaded file
res.writeHead(200, {'content-type': 'text/html'});
res.end('blogginnlegg1');
});
req.pipe(busboy);
});
//get file?
router.get('/file/:id', function(req, res, next){
gfs.findOne({ _id: req.params.id }, function (err, file) {
if (err) return res.status(400).send(err);
if (!file) return res.status(404).send('');
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');
var readstream = gfs.createReadStream({
_id: file._id
});
readstream.on("error", function(err) {
console.log("Got error while processing stream " + err.message);
res.end();
});
readstream.pipe(res);
});
});

File upload in Nodejs using Connect+formidable

I am not able to upload the file using Connect framework. I have refered the link Connect . Below is my code
app.use(connectDomain())
.use(connectRoute(function (router) {
router.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(JSON.stringify({fields: fields, files: files}));
});
I am getting always the response as below
received upload:
{"fields":{},"files":{}}
example given in formidable module..
var files = [],
fields = [];
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);

Resources