Monday, 15 May 2017

How to serve images in a folder in Sailsjs?

How to serve bunch of images in sails.js? Suppose, my API server has a controller for user, to upload images and it's stored in each users' folder in server.

// Image upload
var userId = req.param('id');
req.file('image').upload({
  maxBytes: 2000000,
  // set custom upload dir path name
  dirname: require('path').resolve(sails.config.appPath, 'assets/images/', userId)
}, function whenDone(err, uploadedFiles){
  if (err) {
      return res.negotiate(err);
  }
  // if no file uploaded, response with error
  if (uploadedFiles.length === 0) {
      return res.badRequest('No file');
  } else {
      User_images.create({
         userId: userId,
         avatarFd: uploadedFiles[0].fd
      })
      .exec(function(err, result){
         if (err) {
            return res.serverError(err);
         } else {
            return res.ok('image saved');
         }
      })
  }

});

Basically, the image location successfully saved in User_images model, and the file saved in assets/images/{userid} folder. So, how can I serve all images of a particular user to a frontend application?



via Zuzu Softman

No comments:

Post a Comment