node.js 使用multer上传时如何限制文件大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34697502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to limit the file size when uploading with multer?
提问by Merijn de Klerk
I'm making a simple file upload system with multer:
我正在用multer制作一个简单的文件上传系统:
var maxSize = 1 * 1000 * 1000;
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'public/upload');
},
filename: function (req, file, callback) {
callback(null, file.originalname);
},
onFileUploadStart: function(file, req, res){
if(req.files.file.length > maxSize) {
return false;
}
}
});
var upload = multer({ storage : storage}).single('bestand');
router.post('/upload',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
console.log(req.file);
res.redirect(req.baseUrl);
});
});
This all works fine and the file gets uploaded. The only thing that is not working is the limit on the max size. I made it so that onfileupload start the size of the file gets checked and if its to big it will return false. But the file still just gets uploaded.
这一切正常,文件被上传。唯一不起作用的是最大尺寸的限制。我这样做是为了让 onfileupload 开始检查文件的大小,如果它太大,它将返回 false。但文件仍然刚刚上传。
It seems that onFileUploadStartisn't doing anything at all. I tried to console.logsomething in it, but nothing.
似乎onFileUploadStart根本没有做任何事情。我试图在里面console.log做点什么,但什么也没有。
What am I doing wrong? How can I limit the file size when uploading with multer?
我究竟做错了什么?使用multer上传时如何限制文件大小?
回答by mscdex
There is no onFileUploadStartwith the new multerAPI. If you want to limit the file size, you should instead add limits: { fileSize: maxSize }to the object passed to multer():
onFileUploadStart新multerAPI没有。如果你想限制文件大小,你应该添加limits: { fileSize: maxSize }到传递给的对象multer():
var upload = multer({
storage: storage,
limits: { fileSize: maxSize }
}).single('bestand');

