How to serve images in a folder in Sailsjs?

为君一笑 提交于 2019-12-14 04:10:12

问题


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?


回答1:


I have found the best approach for this is to save just the filename not the full file descriptor. Using your code above you can get the filename from the file descriptor using a simple regex:

// Image Upload
var userId = req.param('id');
req.file('image').upload({
  maxBytes: 2000000,
  // set custom upload dir path name
  dirname: '../../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 {
  // Get the file descriptor
  var f = uploadedFiles[0].fd;
  // return just the filename and use this instead
  var filename = f.replace(/^.*[\\\/]/, '');
  User_images.create({
     userId: userId,
     avatarFd: filename
  })
  .exec(function(err, result){
     if (err) {
        return res.serverError(err);
     } else {
        return res.ok('image saved');
     }
  })
  }
});

Now you can create a controller that returns images for a specific user by passing in that users id, lets call it myimages:

'myimages' : function (req, res) {
  var userId = req.param('id');
  // find images by userId
  User_images.find({userId : userId},function (err, images) {
    if(err) {
      console.log(err);
      return res.serverError('An error occured while finding images');
    }
    if(!images){
      console.log("No Images Found"); 
      return res.notFound();
    }
    res.view({
      images : images
    })
  });
},

In the myimages view, you can then iterate through the images, appending the userId and filename to the image src.

<% _.each(images, function(image) { %>
  <img src="/images/<%= image.userId %>/<%= image.avatarFd %>">
<% }) %>


来源:https://stackoverflow.com/questions/43992808/how-to-serve-images-in-a-folder-in-sailsjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!