当我在NodeJS中使用multer上传图像文件时,我想检查它的真实类型。例如,当我检查文件的mimtype或ext时,如果上传照片的ext从rar变为JPEG。服务器将接受文件,但它应该。谁能帮助我的文件筛选?
var upload = multer({
storage: storage,
dest: "uploads/",
fileFilter: function (req, file, cb) {
if (
file.mimetype !== "image/png" &&
file.mimetype !== "image/gif" &&
file.mimetype !== "image/jpeg"
) {
return cb(null, false);
} else {
cb(null, true);
}
},
});
检查文件的实际类型的唯一方法是读取其内容。当“文件过滤器”在文件上传中发挥作用。服务器实际上并不拥有这个文件,所以'file'参数只有一些非常有限的属性。
因此,最好在客户端检查文件类型,如果文件类型不匹配或任何您想要的,那么在一开始就拒绝请求,无论如何,您可以在express http方法的回调函数中检查实际的文件类型,因为文件被分配在服务器的某个地方(为此,我使用了'file-type'包)`
const storage = multer.memoryStorage()
const upload = multer({
storage: storage
})
const FileType = require('file-type')
app.post('/uploadfile', upload.single('file'), async (req, res) => {
console.log(Object.keys(req.file))
console.log(await FileType.fromBuffer(req.file.buffer));
res.send()
}) `
也许您可以在中间件中做些什么,因为我在三周前学会了Node.js,所以我就把它留在这里。