我使用fileFilter
插件的multer
选项来决定是否应将图片保存到服务器上。
在fileFilter
函数中,我想检查这些图像的magic bytes
,以确保它们是真实的图像并且格式正确。 Multer
仅公开文件,即json array
上传的图片文件,如下所示。但我需要实际图片文件来检查magic bytes
。
{ fieldname: 'file',
originalname: 'arsenal-home-kit.jpg',
encoding: '7bit',
mimetype: 'image/jpeg' }
我在以下代码中评论了我的详细问题。我的尝试到目前为止;
var storage = multer.diskStorage({
destination: __dirname + '/../public/images/',
filename: function (req, file, cb) {
console.log(file.originalname);
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) return cb(err);
cb(null, raw.toString('hex') + path.extname(file.originalname))
})
}
});
var upload = multer({
storage: storage,
fileFilter: function (req, theFile, cb) {
// using image-type plugin to check magic bytes
// I need actual image file right at here.
// theFile is json array, not the image file.
// How to I get the actual image file to check magic bytes.
if (imageType(theFile).ext === "jpg") {
// To accept the file pass `true`, like so:
cb(null, true);
} else {
// To reject this file pass `false`, like so:
cb(null, false);
}
}
});
P.S。我决定使用image-type插件来检查这些神奇的字节。
答案 0 :(得分:2)
在启动文件上载之前调用fileFilter,因此它无法访问文件数据。 这是类似的请求https://github.com/expressjs/multer/issues/155 如你所见,它在路线图中。
目前,您可以将文件下载到临时目录,然后验证它并移动到目标目录或删除。
在我的应用程序中,我使用两种类型的验证器:首先上传前(非常有限)和上传后的第二种类型(mime检查可以在之后)。