gpt4 book ai didi

node.js - 如何在不使用 multer 和 node js 检查文件扩展名的情况下确定文件的真实类型

转载 作者:行者123 更新时间:2023-12-03 12:17:47 26 4
gpt4 key购买 nike

我想在使用 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);
}
},
});

最佳答案

检查文件实际类型的唯一方法是读取其内容。当'fileFilter'在文件上传中起作用时。服务器实际上并不拥有该文件,因此"file"参数只有一些非常有限的属性。

所以最好在客户端检查文件类型,如果文件类型不匹配或任何你想要的,一开始就拒绝请求,无论如何你可以在express http方法的回调函数中检查实际文件类型,因为文件在服务器某处分配(我为此目的使用“文件类型”包)`

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()
}) `

也许你可以在中间件中做一些事情,因为我 3 周前学习了 node.js,所以我就把它留在这里。

关于node.js - 如何在不使用 multer 和 node js 检查文件扩展名的情况下确定文件的真实类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63689474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com