简体   繁体   中英

Check uploaded file extension in Sails js

How we can check uploaded file extension in sails js? I tried on skipper and multer but have no result. any suggestion?

You should use saveAs options for each file before saving.

var md5 = require('md5');
module.exports = {

  testUpload:function(req,res){

     // setting allowed file types
     var allowedTypes = ['image/jpeg', 'image/png'];

     // skipper default upload directory .tmp/uploads/
     var allowedDir = "../../assets/images";

    // don not define dirname , use default path
    req.file("uploadFiles").upload({
       saveAs:function(file, cb) {
          var d = new Date();
          var extension = file.filename.split('.').pop();
          // generating unique filename with extension
          var uuid=md5(d.getMilliseconds())+"."+ extension;

          // seperate allowed and disallowed file types
          if(allowedTypes.indexOf(file.headers['content-type']) === -1) {
            // save as disallowed files default upload path
            cb(null,uuid);
          }else{
            // save as allowed files
            cb(null,allowedDir+"/"+uuid);
          }
       }
    },function whenDone(err,files){
       return res.json({
         files:files,
         err:err
        });
      });
    }
 }

Just get uploaded files array and check last chunk of string after dot.

req.file('file').upload({
  maxBytes: 2000000,
  dirname: 'uploadFolder'
}, function (error, files) {
  if (error) return sails.log.error(error);

  // You have files array, so you can do this
  files[0].fd.split('.').pop(); // You get extension
}

What is going on here? When upload is finished you will get array of files with their filenames. You can get data from that array and see where this file is located (full path).

The last thing is splitting string by dots and get last item from the array with pop() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM