I would not recommend using a binary file to store images directly in your db. If your users want to upload images, it’s kind of a pain, and I don’t think that waterline supports streaming to the database. There is an alternative though!
Mongodb has a gridfs function that breaks large files into pieces and saves them for you.
The Sails file download library, skipper , has an adapter concept (such as a waterline) that allows you to connect an adapter to a download file. There the adapter is called skipper-gridfs , which does it for you! I used this and it is very easy to use. What are you doing:
Define the model sails, call it Image, it has the properties filename and filedescriptor
filedescriptor - , mongo . , ( ) gridfs filedescriptor. ( ) gridfs .
:
var adapter = require('skipper-gridfs');
upload : function (req, res, next) {
var params = req.params.all();
var gf = _gridfs;
req.file('file').upload(
{
adapter:adapter,
uri:constring
},
function (err,uploadedFiles){
if (err) {return res.send(err);}
var imagePromiseArray = [];
_.each(uploadedFiles,function(file){
var imageParams = {
filename:file.filename,
fileDescriptor:file.fd
};
imagePromiseArray.push(Image.create(imageParams));
});
Promise
.all(imagePromiseArray)
.then(function(results){
res.status(200);
return res.send(results);
})
.catch(function(err){
res.status(500);
res.send(err);
});
});
},
:
var mime = require('mime');
download: function (req, res, next) {
var params = req.params.all();
Image
.findOne(params.id)
.then(function (image) {
debugger;
_gridfs.read(image.fileDescriptor, function (err, data) {
if (err) {
res.status(500);
res.json(err);
}
if (!data) {
res.status(404);
res.json({error: 'image not found'});
} else {
res.setHeader('Content-disposition', 'attachment; filename=' + image.filename);
var type = mime.lookup(image.filename);
res.setHeader('Content-type', type);
res.send(data);
}
});
})
.catch(function (err) {
res.json(err);
});
},