当Multer的文件过大时如何向客户端发送响应

我正在使用NodeJs Multer上传文件。 当文件用户尝试上传时,我需要将响应发送回客户端。 问题是, onFileSizeLimit只有文件作为参数,我不知道如何发送响应客户端。 我需要做的是基本如下所示:

 app.use('/users/gyms/upload-logo', multer({ // other settings here then: onFileSizeLimit: function (file) { // but res (response) object is not existing here res.json({ message: "Upload failed", status: MARankings.Enums.Status.FILE_TOO_LARGE // status: -6 }); } }); 

在那里存在的res对象剂量,我想知道什么是最好的方式发送某种types的响应客户端。

在这种情况下,最好记住Multer本身就是Express调用来获得响应的(中间件)函数。

你也许可以试试这个:

 app.use('/users/gyms/upload-logo', function(req, res, next) { var handler = multer({ // other settings here then: onFileSizeLimit: function (file) { // res does exist here now :) res.json({ message: "Upload failed", status: MARankings.Enums.Status.FILE_TOO_LARGE // status: -6 }); } }); handler(req, res, next); }); 

这基本上把multer别名处理,从Expresscallback中传递req, res, next并且意味着你可以访问Multerconfiguration中的req, res, nextvariables。

我没有testing过这个,但我认为这个理论是有道理的!

尝试这个:

 app.use('/users/gyms/upload-logo', multer({ // other settings here then: onFileSizeLimit: function (file) { // but res (response) object is not existing here file.error = { message: "Upload failed", status: MARankings.Enums.Status.FILE_TOO_LARGE // status: -6 }; }, onFileUploadComplete: function (file, req, res) { if (file.error){ res.send(file.error); } } }); 

这个问题还没有得到作者的彻底解决。 这个github 问题有很多关于它的讨论:

我在当前的项目中使用了一项工作

文件:make-middleware.js在这个函数的末尾改变“function done(err)”

replace第52行: onFinished(req, function () { next(err) })

使用:第52行: onFinished(req, function () { if(err.code == 'LIMIT_FILE_SIZE') { req.fileSizeError = 1; next() } else next(err) })

而在应用程序文件中,您可以更改代码

 app.post('/upload', upload.single('upload'), function (req, res, next) { if(typeof req.fileSizeError != "undefined") { res.send({"error":"File too large"});// to display filesize error } else { res.send({"file":req.file}); // when file uploaded successfully } }); 

multer文件对象实际上包含一个属性,指示文件是否超出了大小限制。 请参阅https://www.npmjs.com/package/multer#multer-file-object

为了只接受一个最大大小为2 MB的文件和“data”这个名字,我做了这样的事情:

 app.use(multer({ dest: "./uploads/", putSingleFilesInArray: true, // see https://www.npmjs.com/package/multer#putsinglefilesinarray limits: { files: 1, fileSize: 2097152 // 2 MB } })); app.post("/foo", function(request, response) { if (!request.files.hasOwnProperty("data")) { // 400 Bad Request return response.status(400).end(); } var file = request.files.data[0]; if (file.truncated) { // 413 Request Entity Too Large console.log("Request aborted."); return response.status(413).end(); } // do stuff with file });