Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js and multer: how to know when the files are all uploaded?

I'm using Multer module for file uploads. While it all works ok, there's a warning at the end of their github page, which reads: "WARNING: req.body is fully parsed after file uploads have finished. Accessing req.body prematurely may cause errors."

This has got me really worried. I just can't find a way to let the .post middleware know when the file(s) have been uploaded and req.body is ready to use. Here's 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?
    });

While I am aware of onParseEnd, but I don't know how to implement it, so that I have at least some kind of information about the upload process being finished.

like image 536
uglycode Avatar asked Apr 04 '15 23:04

uglycode


3 Answers

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

  • onParseStart
  • onFileUploadStart/onFileUploadData...
  • onFileUploadComplete
  • onParseEnd
  • your .post() handler
like image 170
mikijov Avatar answered Oct 12 '22 19:10

mikijov


As of 2018, onFileUploadComplete(file, req, res) is no longer part of multer.

like image 33
Peter Murphy Avatar answered Oct 12 '22 18:10

Peter Murphy


If I understand the documentation correctly the warning is only applicable to the event handlers you can pass to multer itself. When the request reaches your handler multer is already done and all files are already uploaded.

The problem exists for example in the rename event which you already use, but this function actually receives four arguments fieldname, filename, req, res. That means you have access to the request before it is fully parsed.

like image 2
Gigo Avatar answered Oct 12 '22 19:10

Gigo