Do stuff with multiple files when uploading them using node-formidable with Express
Problem
Uploading files with node-formidable on Express is as simple as this
app.post('/upload', function(req, res) {
// do something with req.files
});
The files are now saved
The form: (multiple="multiple" is a HTML5 feature that allows users to select Multiple Files to upload)
If i add this line to the upload code
console.log(req.files.upload.path);
When uploading one file, the path shows up in the console. But when I upload more than one file it just says undefined in the console. How do I get the log stuff for each file? Using a for loop?
The node-formidable example on GitHub logs every file when you upload several: https://github.com/felixge/node-formidable/blob/master/example/upload.js (I tried using this code in Express, didn’t work) It does exactly what I want, but how do I do this in an Express app?
Solution
It works by moving the line below to the bottom of the app.configure function. Read about the importance of order regarding middleware in Express here: http://expressjs.com/guide.html#middleware
app.use(express.bodyParser({ uploadDir:__dirname + '/public/uploads' }));
And by using this handler:
app.post('/upload', function(req, res){
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);
});
Thanks Ryan!
Discussion
View additional discussion.