我正在使用ExpressJS的multer。我想将文件上传限制为0.5 MB。
var limits = { fileSize: 0.5 * 1024 * 1024 };
var upload = multer({ dest: './public/uploads/', limits: limits
}).single('upl')
app.post('/',upload, function (req, res) {
upload(req, res, function (err) {
if (err) {
console.log("cs " + err);
return
}
res.end('You new avatar is uploaded')
// Everything went fine
})
})
当文件小于0.5 MB时,我可以看到“你上传了新的头像”#39;但是当它结束时,我明白了,
Error: File too large
at makeError (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-error.js:12:13)
at abortWithCode (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-middleware.js:77:22)
at FileStream.<anonymous> (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\multer\lib\make-middleware.js:139:11)
at emitNone (events.js:80:13)
at FileStream.emit (events.js:179:7)
at PartStream.onData (C:\Users\Owner\Desktop\nodejs projects\dummy\node_modules\busboy\lib\types\multipart.js:220:18)
at emitOne (events.js:90:13)
at PartStream.emit (events.js:182:7)
at readableAddChunk (_stream_readable.js:153:18)
at PartStream.Readable.push (_stream_readable.js:111:10)
显然,我绝不希望最终用户看到这一点。我该如何妥善处理?
答案 0 :(得分:4)
尝试像这样重写(删除&#34;上传&#34;首先):
app.post('/', function (req, res) {
upload(req, res, function (err) {
if (err) {
console.log("cs " + err);
return
}
res.end('You new avatar is uploaded')
// Everything went fine
})
答案 1 :(得分:1)
我已经在server.js
文件的末尾创建了Express处理程序。
app.use()
之后放置处理程序函数,请检查来自multer的错误,然后发送所需的数据。
我的代码发送了LIMIT_FILE_SIZE
字符串。app.use(() => (err: Error, req: Request, res: Response, next: NextFunction) => {
if (err instanceof multer.MulterError) {
return res.status(418).send(err.code);
}
});
文档:http://expressjs.com/en/guide/error-handling.html#error-handling