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 us
Solution 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 %>">
<% }) %>
Post a Comment for "How To Serve Images In A Folder In Sailsjs?"