如何防止文件被Multer上传,除非它们是图像?

正如标题所说。

我到处找,找不到答案。


码:

var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image"); 

问题

如果我select的话,这并不妨碍我上传PDF。

文档声明您应该使用fileFilter可能跳过file upload。
fileFilterhttps://github.com/expressjs/multer#filefilter

 Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this: function fileFilter (req, file, cb) { // The function should call `cb` with a boolean // to indicate if the file should be accepted // To reject this file pass `false`, like so: cb(null, false) // To accept the file pass `true`, like so: cb(null, true) // You can always pass an error if something goes wrong: cb(new Error('I don\'t have a clue!')) } 

从文档我会假设传入file有一个属性mimetypehttps://github.com/expressjs/multer#api )。 如果你想跳过,这可能是一个很好的决定提示。

编辑:这个GH问题( https://github.com/expressjs/multer/issues/114#issuecomment-231591339 )包含一个很好的例子,用法。 不仅要查看文件扩展名是很重要的,因为这可以很容易地重命名,但也可以考虑MIMEtypes。

 const path = require('path'); multer({ fileFilter: function (req, file, cb) { var filetypes = /jpeg|jpg/; var mimetype = filetypes.test(file.mimetype); var extname = filetypes.test(path.extname(file.originalname).toLowerCase()); if (mimetype && extname) { return cb(null, true); } cb("Error: File upload only supports the following filetypes - " + filetypes); } }); 

HTH