Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate file type before upload use SailsJS Skipper

As the title, now I can not check file type before upload. I only verify and don't allow save data after file uploaded successfully. Below is a basic code

updateAvatar : function(data, context, req, res) {
  req.file('avatar').upload({
      dirname: '../../assets/images/avatar'
    }, function (err, files) {

    var allowExts = ['image/png', 'image/gif', 'image/jpeg'];

    if (err)
      return res.serverError(err);

    if (files.length === 0) 
      return res.badRequest('No file was uploaded!');

    if (allowExts.indexOf(files[0].type) == -1)
      return res.badRequest('File type is not supported!');

    // save database here
  });
}

What should I do for correct code? Sorry for my bad English! Thanks a lot!

like image 730
Thanh Dao Avatar asked Aug 31 '15 03:08

Thanh Dao


1 Answers

This took me time to research on, all credits to Darkstra who gave an idea of where we can get the raw file properties, like the content-type or even the file name, where we can split to get the file extension and do our checkings

you can check out his answer here

The main thing is to take note of this

req.file('foo')._files[0].stream which contains everything we need to handle our file, you can console.log it to see the content of it.

At least you can do any manipulation of your choice.

like image 93
Theophilus Omoregbee Avatar answered Oct 19 '22 12:10

Theophilus Omoregbee