【问题标题】:how to determine real type of file without check file extension using multer and node js如何使用 multer 和 node js 在不检查文件扩展名的情况下确定文件的真实类型
【发布时间】:2020-09-28 15:51:28
【问题描述】:

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

【问题讨论】:

    标签: node.js express upload multer


    【解决方案1】:

    检查文件实际类型的唯一方法是读取其内容。 当 '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,所以我就把它留在这里。

    【讨论】:

      猜你喜欢
      • 2010-10-03
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      相关资源
      最近更新 更多