如果文件不存在,则在multer中引发错误

时间:2018-07-27 08:08:02

标签: node.js file express multer

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

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')
  }
}

1 个答案:

答案 0 :(得分:0)

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

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

我认为Multer的文件数不能超过最小限制。