【问题标题】:How to prevent files from being uploaded with Multer unless they are images?除非它们是图像,否则如何防止文件被 Multer 上传?
【发布时间】:2017-01-03 05:19:43
【问题描述】:

正如标题所说。

我到处找,找不到答案。


代码:

var upload = multer({dest:"./public/images/uploads/", limits: {fileSize: 250000}}).single("image");

问题

如果我选择这样做,这不会阻止我上传 pdf。

【问题讨论】:

    标签: javascript node.js multer


    【解决方案1】:

    文档说明您应该使用 fileFilter 来跳过文件进行上传。
    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!'))
    
    }
    

    从文档中,我假设传入的 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);
      }
    });
    

    HTH

    【讨论】:

    • 感谢您的提示!但这不是一个与我的案例相关的例子的完整答案:)
    • 我确实认为这非常相关。您链接的 github 问题使用相同的功能(fileFilter)。我还希望检查 mime 类型,因为文件扩展名很容易出错。不理解否决票。我认为额外的 if 子句不会成为问题。 github.com/expressjs/multer/issues/114#issuecomment-231591339 :-)
    • 你没有在你的答案中包含这个:/你编辑你的答案怎么样? :)
    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2019-09-20
    • 2014-08-01
    • 2015-12-26
    • 1970-01-01
    • 2014-01-17
    相关资源
    最近更新 更多