Cod*_*000 4 javascript node.js multer
正如标题所说。
我到处寻找,找不到答案。
代码:
var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image");
Run Code Online (Sandbox Code Playgroud)
问题
如果我选择上传 pdf,这并不妨碍我上传 pdf。
文档指出您应该使用 fileFilter 来跳过要上传的文件。
文件过滤器(https://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!'))
}
Run Code Online (Sandbox Code Playgroud)
从文档中我假设传入的file有一个属性mimetype(https://github.com/expressjs/multer#api)。如果您想跳过,这可能是做出决定的一个很好的提示。
编辑: 这个 GH 问题(https://github.com/expressjs/multer/issues/114#issuecomment-231591339)包含一个很好的用法示例。重要的是,不仅要查看文件扩展名,因为它可以轻松重命名,还要考虑 mime 类型。
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);
}
});
Run Code Online (Sandbox Code Playgroud)
华泰