sreepurna
sreepurna

Reputation: 1662

If file is not present throw error in multer

I am using multer for storing a files in disk. I have written the code for error conditions for invalid file extension, file size, no. of files & for successful storage. When I tested in this in postman, I have not given any file for choosefile field. Then also my code produces result as file is uploaded successfully. So, now i want to throw error when file is not selected also. I want to know whether we have any way to do that?

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

Upvotes: 1

Views: 2633

Answers (1)

Akshay Alenchery
Akshay Alenchery

Reputation: 181

Multer adds a body object and a file or files object to the request object. So you can check

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

I don't think so Multer has a min number of files limit.

Upvotes: 2

Related Questions