Do stuff with multiple files when you upload them using node-generated using Express

Uploading files using node-formidable on Express is as easy as it is

app.post('/upload', function(req, res) { // do something with req.files }); 

Files are now saved

Form: (multiple = "multiple" is an HTML5 function that allows users to select multiple files to upload)

 <form method="post" enctype="multipart/form-data" action="upload"> <input type="text" name="title"/> <input type="file" name="upload" multiple="multiple"/> <input type="submit" value="upload" id="s3form_submit"/> </form> 

If I add this line to the download code

 console.log(req.files.upload.path); 

When downloading a single file, the path is displayed in the console. But when I upload multiple files, it just says undefined in the console. How to get log material for each file? Using a for loop?

An example of node education in GitHub registers every file when loading several: https://github.com/felixge/node-formidable/blob/master/example/upload.js (I tried to use this code in Express, it didn’t work) It does exactly what I want, but how to do it in an Express application?

+7
source share
2 answers

It works by moving the line below at the bottom of the app.configure function. Read about the importance of ordering for middleware in Express here: http://expressjs.com/guide.html#middleware

 app.use(express.bodyParser({ uploadDir:__dirname + '/public/uploads' })); 

And 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!

+8
source

So req.files can be an array. Try making console.log(req.files) in the handler and see how it looks ... But I think you better just do it, as in your example. You can make it work by simply removing ../test/common require at the top and changing the constants to static values ​​(for example, use __dirname + '/uploads' instead of TEST_TMP ).

Handler:

 var form = new formidable.IncomingForm(), files = [], fields = []; form.uploadDir = __dirname + '/uploads'; 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); 

Now the files are in __dirname + '/uploads' , named as the output on the console (and the answer, as you can see in the end handler).

+1
source

All Articles