使用multer存储文件

时间:2018-07-26 13:47:43

标签: node.js express multer

我正在使用Express,multer从桌面存储文件。当我不传递任何文件时,它也在生成文件已成功上传的消息,而不是抛出错误。我该怎么解决?

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

0 个答案:

没有答案