Skip to content

Instantly share code, notes, and snippets.

@1nstinct
Last active March 14, 2018 08:37
Show Gist options
  • Save 1nstinct/6a7481385569da39eded to your computer and use it in GitHub Desktop.
Save 1nstinct/6a7481385569da39eded to your computer and use it in GitHub Desktop.
nodejs sails gridfs upload, view, delete image/file
/**
* ImageController
*
* @description :: Server-side logic for managing Images
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
module.exports = {
uploadImage: function(req, res) {
req.file('image').upload({
adapter: require('skipper-gridfs'),
uri: 'mongodb://localhost:27017/restaurant.images'
}, function (err, uploadedImages) {
if (err) return res.negotiate(err);
var obj = {};
if(req.param('product_id')) {
obj = Product;
} else if(req.param('product_category_id')) {
obj = ProductCategory;
} else {
return res.badRequest({message: 'Parent entity not found'});
}
var id = req.param('product_id') || req.param('product_category_id');
obj.findOne({id: id}).then(function(found) {
if(!found) throw new Error('Related entity not found');
return found;
}).then(function(found) {
for(var i in uploadedImages) {
if(!found.images) found.images = [];
found.images.push(uploadedImages[i].fd);
}
obj.update({id: id}, {images: found.images}).exec(function(err, updated) {
return res.ok({
files: uploadedImages,
textParams: req.params.all()
});
})
}).catch(function(error){
console.error(error);
return res.badRequest({message: error.message});
});
});
},
viewImage: function(req, res) {
var blobAdapter = require('skipper-gridfs')({
uri: 'mongodb://localhost:27017/restaurant.images'
});
var fd = req.param('id'); // value of fd comes here from get request
blobAdapter.read(fd, function(error , file) {
if(error) {
res.json(error);
} else {
res.contentType('image/jpeg');
res.send(new Buffer(file));
}
});
},
delete: function(req, res) {
var blobAdapter = require('skipper-gridfs')({
uri: 'mongodb://localhost:27017/restaurant.images'
});
var fd = req.param('id'); // value of fd comes here from get request
blobAdapter.rm(fd, function(error , file) {
if(error) {
res.json(error);
} else {
var Promise = require('q');
// remove relations
Promise.all([
Product.findOne({images: fd}),
ProductCategory.findOne({images: fd})
])
.spread(function(product, product_category){
if(product) {
var i = product.images.indexOf(fd);
if (i > -1) {
product.images.splice(i, 1);
}
Product.update({images: fd}, {images: product.images}).exec(function(err, updated) {
if(err) throw new Error(err);
return res.ok({
removed_image: fd,
product_updated: updated[0].id
});
});
} else if(product_category) {
var i = product_category.images.indexOf(fd);
if (i > -1) {
product_category.images.splice(i, 1);
}
ProductCategory.update({images: fd}, {images: product_category.images}).exec(function(err, updated) {
if(err) throw new Error(err);
return res.ok({
removed_image: fd,
product_category_updated: updated[0].id
});
});
} else {
return res.ok({
removed_image: fd
});
}
})
.catch(function(error){
console.error(error);
return res.badRequest({message: error});
});
}
});
}
};
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'/': {
view: 'homepage'
},
'post /image': 'ImageController.uploadImage',
'get /image/:id': 'ImageController.viewImage',
'delete /image/:id': 'ImageController.delete',
/***************************************************************************
* *
* Custom routes here... *
* *
* If a request to a URL doesn't match any of the custom routes above, it *
* is matched against Sails route blueprints. See `config/blueprints.js` *
* for configuration options and examples. *
* *
***************************************************************************/
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment