node.js:file upload using multer in sails.js

Viewed 1350

I would like to integrate multer https://www.npmjs.com/package/multer file upload package in my sails.js framework application unfortunately there is no tutorial avaliable for it.

Can anyone give a guidance how to do it in sails.js??

2 Answers

I also came across this problem and wasn't able to find anything on internet but after reading sails.js documentations, I figured out a way to upload files.

Internally sails.js uses skipper to upload files and the code is pretty straightforward for it.

var uploadFile = req.file('user_picture');
uploadFile.upload({ dirname: filePath }, function onUploadComplete(err, files) {
  if (err) return res.serverError(err);
  //  IF ERROR Return and send 500 error
  console.log(files);
});

The user_picture is the name of the variable in your form.

Hope this helps!

module.exports.http = {
  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',
      'fileMiddleware',
      'bodyParser',
      'compress',
      'poweredBy',
      'router',
      'www',
      'favicon',
    ],
    /***************************************************************************
    * *
    * The body parser that will handle incoming multipart HTTP requests. *
    * *
    * https://sailsjs.com/config/http#?customizing-the-body-parser *
    * *
    ***************************************************************************/
    bodyParser: (function () {
      const bodyParser = require('body-parser');
      bodyParser.json();
      bodyParser.urlencoded({ extended: true });
      return bodyParser();
    })(),
    fileMiddleware: (function () {
      const multer = require('multer');
      const upload = multer();
      return upload.fields([{ name: 'images' }, { name: 'profile' }, { name: 'cover' }]);
    })(),
  }
};

You can try this. It will override skipper.

Related