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

三世轮回 提交于 2019-12-01 05:18:24
mikijov

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

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.

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

You can know it easily, there is option available in multer called

  • onFileUploadComplete(file, req, res)

You can use this and send 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
    }

}));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!