javascript - 除非文件是图像,否则如何防止使用 Multer 上传文件?

标签 javascript node.js multer

正如标题所说。

我到处找,找不到答案。


代码:

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

问题

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

最佳答案

文档说明您应该使用 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

关于javascript - 除非文件是图像,否则如何防止使用 Multer 上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432403/

相关文章:

javascript - 动态填充 Bootstrap 选择器 : change event doesn't work

javascript - 减少 Vue 提供的文件数量

node.js - 使用 Puppeteer 抓取 Google map 搜索结果链接

angularjs - 如何使用多个文件输入元素上传文件?

javascript - 将 canvas.toDataURL() 作为 FormData 发送

javascript - 如何将 Javascript 符号设置为对象键?

node.js - TFS 上的 Node 构建问题

javascript - 尝试在我的第一个 react 网站上建立一个基本的搜索栏

node.js - 使用 Multer 未将图像文件名插入到数据库中

javascript - PHP Cookie 未通过 AJAX 设置