【问题标题】:If file is not present throw error in multer如果文件不存在,则在 multer 中抛出错误
【发布时间】:2020-04-03 20:34:28
【问题描述】:

我正在使用 multer 将文件存储在磁盘中。我已经为无效文件扩展名、文件大小、否的错误条件编写了代码。文件和成功存储。当我在邮递员中对此进行测试时,我没有为选择文件字段提供任何文件。然后我的代码也会产生结果,因为 文件已成功上传。所以,现在我想在未选择文件时也抛出错误。我想知道我们是否有办法做到这一点?

var storage = multer.diskStorage({
  destination: function (req, file, callback) {
    //TODO: need to change the storage path for each user
    //TODO: if path is not valid then check for the directory existance
    //ToDO: if directory not existing create new directory
    callback(null, './storage/cust_88ae31d4-47c5-4f70-980e-7b473ba20ef9')
  },
  filename: function (req, file, callback) {
    console.log(file)
    console.log(typeof file.originalname)
    callback(null, file.originalname)
  }
})

var uploadFromDesktop = multer({
  storage: storage,
  limits: {
    fileSize: maxSize
  },
  fileFilter: function (req, file, callback) {
    var mimeTypeList = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']
    if (mimeTypeList.indexOf(file.mimetype) <= -1) {
      var cusError = new Error('File type is invalid')
      cusError.code = 'INVALID_FILE_TYPE'
      cusError.field = file.fieldname
      return callback(cusError)
    } else {
      return callback(null, true)
    }
  }
}).array('choosefile', maxNum) // given name of file selector


function upload(req, res) {
  switch (req.params.provider) {
    case 'desktop':
      uploadFromDesktop(req, res, function (err) {
        if (err) {
          console.log(err)
          console.log(err.code)
          switch (err.code) {
            case 'LIMIT_UNEXPECTED_FILE':
              res.end('Number of files choosen for uploading are greater than ' + 2)
              break
            case 'LIMIT_FILE_SIZE':
              res.end('Choosen file size is greater than ' + maxSize)
              break
            case 'INVALID_FILE_TYPE':
              res.end('Choosen file is of invalid type')
              break
            case 'ENOENT':
              res.end('Unable to store the file')
              break
          }
        }
        res.end('File is uploaded successfully')
      })
      break;
    case 'cloud':
      uploadFromCloud(req, res)
      break;
    default:
      res.send('unable to store the file')
  }
}

【问题讨论】:

  • 那么您是说在这种情况下 multer 不会记录错误?
  • 可能是詹姆斯!由于我没有处理该案例,因此它可能应该崩溃了。但没有发生过这样的事情
  • 好吧,你从 multer 中注销了一个错误,所以除非没有返回一个错误,否则你会在控制台中看到它。我想看看multer 是否有一个最小文件配置但没有出现,我认为你只需要一个简单的if (!req.files.length) { // return error }。虽然如果没有文件上传,fileFilter 代码肯定会抛出错误?
  • @James 我将 req.files 设为未定义

标签: node.js file express multer


【解决方案1】:

Multer 将一个主体对象和一个或多个文件对象添加到请求对象中。所以你可以检查

if(!req.files.length) req.status(400).send('No files selected')

我不认为 Multer 有最小文件数限制。

【讨论】:

  • 是 res.status(400).send("No file selected")
猜你喜欢
  • 2021-12-02
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
相关资源
最近更新 更多