简体   繁体   中英

Sails.js - file upload

I am working on a Sails.js project at the moment and I would like to upload a file to the server and save the link to that file in my database.

For example, when I click add FILE, it should allow me to select a file from my computer and when I click submit, it should upload the file to the URL that I point ( create the folder if it does not exist).

Can this be accomplished with Sails.js? If yes, how?

Thank you!

This will get you most of the way there: https://github.com/balderdashy/sails/issues/27

You can use https://github.com/aconbere/node-file-utils to create directories, etc. Install it with

npm install file

Require file in the module having code similar to that in .../sails/issue/27.

This blog has has a good example of handling a file upload--it worked for me:

http://maangalabs.com/blog/2014/08/12/uploading-a-file-in-sails/

upload: function  (req, res) {

    // Call to /upload via GET is error
    if(req.method === 'GET')
          return res.json({'status':'GET not allowed'});                        

    var uploadFile = req.file('uploadFile');
    console.log(uploadFile);

    uploadFile.upload(function onUploadComplete(err, files) {

        // Files will be uploaded to .tmp/uploads

        // IF ERROR Return and send 500 error with error
        if (err) return res.serverError(err);                               

        console.log(files);
        res.json({status:200,file:files});
    });
}

The best option is to do this on middleware

aware to check filetypes and route matching otherwise bad actors can upload malicious files

Edit config/http.js like this

serverOptions: {
    timeout: 600000,
  },
  middleware: {

    /***************************************************************************
    *                                                                          *
    * The order in which middleware should be run for HTTP requests.           *
    * (This Sails app's routes are handled by the "router" middleware below.)  *
    *                                                                          *
    ***************************************************************************/

    order: [
      'cookieParser',
      'session',
      'bodyParser',
      'fileUpload', //new middleware
      'compress',
      'poweredBy',
      'router',
      'www',
      'favicon',
    ],

fileUpload middleware code

fileUpload: (function () {
  return function (req, res, next) {
    console.log('Received HTTP request: ' + req.method + ' ' + req.path);
    const uploadRoutes = ['/save-user-profile-image'];
    if (req.method === 'POST' && uploadRoutes.includes(req.path)) {


      req.file('profileImage').upload(
        {
          maxBytes: 10000000,
          dirname: require('path').resolve(sails.config.appPath, 'uploads/'),
          saveAs: `YOUR_FILE_NAME.jpg`
        },
        function (err, files) {
          if (err) {
            console.log('Error: ' + err.message);
            return next(err);
          }

          if (files.length > 0) {
            var uploadedFile = files[0];
            var fileName = uploadedFile.filename;
            var sizeInBytes = uploadedFile.size;
            var path = uploadedFile.fd;

            
         
            req.body.fileName = fileName;
            req.body.sizeInBytes = sizeInBytes;
            req.body.filePath = path;
            req.body.imageName = name;
          
          }

          return next();
        }
      );
    } else {
      return next();
    }
  };
})(),

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