Express.js and multer: how do I know when all files are uploaded?

I use the Multer module to upload files. Although everything is working fine, a warning appears at the end of their github page saying: "WARNING: req.body is fully analyzed after the file upload is complete. Accessing req.body can lead to errors prematurely."

It bothered me a lot. I just can't find a way to notify .post middleware when files are uploaded and req.body is ready to use. Here is my code:

app.js:

app.use(multer({ dest: './uploads/', rename: function (fieldname, filename) { return filename.replace(/\W+/g, '-').toLowerCase() + Date.now(); }, putSingleFilesInArray: true }) ); 

upload.js:

 router.route('/') .get(function(req, res){ res.render('uploads'); }) .post(function(req, res){ //how to wait here for the file to upload? }); 

So far I know onParseEnd, but I don’t know how to implement it, so I have at least some information about the completion of the download process.

+5
source share
3 answers

Multer is part of the router network. This means that the expression will execute the multer first, and only after the multer has completed parsing the form will it continue to execute your .post() handler. The warning on the page is for accessing req.body from req.body callbacks such as onFileUploadData() and the like. Therefore, the order of execution:

  • onParseStart
  • onFileUploadStart / onFileUploadData ...
  • onFileUploadComplete
  • onParseEnd
  • .post() handler
+5
source

If I understand the documentation correctly, this warning only applies to event handlers that you can pass in to fool yourself. When the request reaches your handler, multer is already executed, and all files are already loaded.

The problem exists, for example, in the rename event that you are already using, but this function actually receives four arguments fieldname, filename, req, res . This means that you have access to the request before it is fully analyzed.

+2
source

You can easily know this, there is an option available in the multer called

  • onFileUploadComplete (file, req, res)

You can use this and send a response from here.

https://github.com/expressjs/multer#options

  app.use(multer({ dest: path.join(__dirname, '../uploads/fullsize'), rename: function (fieldname, filename) { return filename.replace(/\W+/g, '-').toLowerCase(); }, onFileUploadStart: function (file) { console.log(file.name + ' is starting ...'); }, onFileUploadComplete: function (file, req, res) { console.log(file.name + ' uploading is ended ...'); console.log("File name : "+ file.name +"\n"+ "FilePath: "+ file.path) }, onError: function (error, next) { console.log("File uploading error: => "+error) next(error) } onFileSizeLimit: function (file) { console.log('Failed: ', file.originalname +" in path: "+file.path) fs.unlink(path.join(__dirname, '../tmpUploads/') + file.path) // delete the partially written file } })); 
0
source

All Articles