Express.js和multer:如何知道文件何时全部上传? [英] Express.js and multer: how to know when the files are all uploaded?

查看:99
本文介绍了Express.js和multer:如何知道文件何时全部上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Multer模块进行文件上传。虽然这一切都可以正常工作,但在github页面末尾有一个警告,内容如下:
警告:文件上传完成后,req.body被完全解析,过早访问请求可能会导致错误。



这让我真的很担心。我找不到一种方法让.post中间件知道文件何时被上传,并且req.body已经可以使用了。这是我的代码:



app.js:

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

upload.js:

 .get(function(req,res){
res.render('uploads');
})
.post(function(req,res){
//如何等待这个文件上传?
});

虽然我知道onParseEnd,但是我不知道如何实现它,所以我至少有一些关于上传过程的信息已经完成。

解决方案

Multer是路由器chanin的一部分。这意味着express将首先执行multer,只有一次multer已经完成了解析,表单才会继续,并将执行传递给您的.post()处理程序。页面上的警告是用于从multer回调访问req.body,如onFileUploadData()等。因此,执行顺序是:




  • onParseStart

  • onFileUploadStart / onFileUploadData ... <
  • onFileUploadComplete

  • onParseEnd

  • 您的.post()处理程序


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.

解决方案

Multer is part of the router chanin. This means that express will execute multer first, and only once multer has completed parsing the form will it continue and pass 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

这篇关于Express.js和multer:如何知道文件何时全部上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆