Reputation: 2101
I am new to node.js. I know this may seem a duplicate question but I looked at many related topics and tried a lot, but this is so complicated...
I use Node.js on server side to upload a file and rename it. the file's new name comes from client side in some hidden field in the form. The problem is that the new name comes in one async function and the file is written in another, so the name is not available when I am writing the file to the stream.
I tried nesting the second call in the callback function of the first, but it didn't fire any more. I tried async.waterfall also, but with no success.
Here is the server-side code :
//--------------------------initializing:--------------------------
var express = require('express');
var busboy = require('connect-busboy');
var path = require('path');
var fs = require('fs-extra');
var bodyParser = require('body-parser');
var formidable = require('formidable');
var urlencodedParser = bodyParser.urlencoded({ extended: true })
var app = express();
app.use(bodyParser());
app.use(busboy());
app.use(express.static(__dirname ));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/a.html');
});
var server = app.listen(SERVER_PORT, function() {
console.log('Listening on port %d', server.address().port);
});
//------------------Here is the main code : ----------------------
//UPLOAD is not logged.
app.post('/upload', function(req, res){
var form = new formidable.IncomingForm();
var fstream;
req.pipe(req.busboy);
var newName ;
form.parse(req, function(err, fields, files) {
newName = fields.hiddenField;
console.log('PARSE');
req.busboy.on('file', function (fieldname, file, filename) {
console.log('UPLOAD');
fstream = fs.createWriteStream(__dirname + '/img/' + newName + '.jpg');
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
}); //where to go next
});
});
});
Thanks for any help.
Upvotes: 1
Views: 2288
Reputation: 12019
If you do not need to use formidable
, you can use connect-busboy
to obtain the field name from the 'POST' request. For a form field defined this way:
<input type="text" name="hiddenField" />
<input type="file" name="fileUpload" />
you can use connect-busboy
to obtain the value from the hiddenField
input:
var newName = null;
app.post('/upload', function(req, res) {
req.pipe(req.busboy);
// fieldName is 'hiddenField'
req.busboy.on('field', function(fieldname, val) {
newName = val;
});
req.busboy.on('file', function (fieldname, file, filename) {
// fieldname is 'fileUpload'
var fstream = fs.createWriteStream(__dirname + '/img/' + newName + '.jpg');
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
}); //where to go next
});
});
The field
event must be handled before the file
event.
Upvotes: 1