Store your files in mongodb easily
$ npm install --save gridfs-easy
Craete a file like db.js:
//require the gridfs-easy and mongoose
var mongoose = require('mongoose');
var gridfsEasy = require('gridfs-easy');
//establish the connection with mongoose
var dbUri = 'mongodb://serverAddress:portNumber/databaseName';
mongoose.connect(dbUri, {useMongoClient: true});
//export the gridfsEasy so that you can use it everywhere
module.exports = new Promise(function (resolve, reject) {
//make sure you've successfully connected
mongoose.connection.on('connected', function () {
//initialize the gridfs-easy
var gfsEasy = new gridfsEasy(mongoose);
resolve(gfsEasy);
});
});
Require the db.js wherever you want. (e.g. pictureRouter.js)
var gfsEasy = require('./db').then(function (gfsEasy) {
//make use of gfsEasy methods (e.g. gfsEasy.getInfoById())
})
A base64 format of the file (e.g. picture, video, pdf, etc.) from fs.files collection with _id will be retrieved:
pictureRouter.route('/getBase64ById')
.get(function (req, res, next) {
gfsEasy.getBase64ById('5ab417d36900a33288af587e', function (err, base64) {
if (err) {}
else { res.json({fileBase64: base64}); }
})
});
A document from fs.files collection with _id will be retrieved:
pictureRouter.route('/getInfoById')
.get(function (req, res, next) {
gfsEasy.getInfoById('5ab417d36900a33288af587e', function (err, info) {
if (err) {}
else {res.json(info);}
})
});
The callback function will be called with info of the document:
{
"_id" : ObjectId("5ab417d36900a33288af587e"),
"filename" : "pic.png",
"contentType" : "binary/octet-stream",
"length" : 13282,
"chunkSize" : 261120,
"uploadDate" : ISODate("2018-03-22T20:53:40.026Z"),
"aliases" : null,
"metadata" : null,
"md5" : "f0b8b7ba4ea9b70b4d21ad28f962f0ac"
}
All documents with the name given as the first parameter will be retrieved as an array from the fs.files collection:
pictureRouter.route('/getAllByName')
.get(function (req, res, next) {
gfsEasy.getAllByName('pic.png', function (err, docsArray) {
if (err) {}
else {
//send the documents to the client
res.json({docs: docsArray});
}
})
});
docs:
[
{
"_id": "5ab4260c26c6441d946b69e4",
"filename": "pic.png",
"contentType": "binary/octet-stream",
"length": 43630,
"chunkSize": 261120,
"uploadDate": "2018-03-22T21:54:20.937Z",
"aliases": null,
"metadata": null,
"md5": "2830695ace2df8a15d3479c432af9f88"
},
{
"_id": "5ab427a726c6441d946b69e6",
"filename": "pic.png",
"contentType": "binary/octet-stream",
"length": 43630,
"chunkSize": 261120,
"uploadDate": "2018-03-22T22:01:11.637Z",
"aliases": null,
"metadata": null,
"md5": "2830695ace2df8a15d3479c432af9f88"
}
]
A base64 format of the image plus the corresponding data URI scheme (e.g. data:image/png;base64,) of a file from fs.files collection with _id will be retrieved:
pictureRouter.route('/getImageById')
.get(function (req, res, next) {
gfsEasy.getImageById('5ab417d36900a33288af587e', function (err, base64) {
if (err) {}
//send the image to the client
// make use of 'image' in HTML( e.g. <img src={{image}}> )
else { res.json({image: base64}); }
})
});
Check whether a file with _id exists in fs.files collection:
gfsEasy.existFile('5ab417d36900a33288af587e', function (err, result) {
if (err) {}
else {
//result is true if file exists, false otherwise
console.log(result)
}
})
Remove a file with _id from fs.files collection:
gfsEasy.removeFile('5ab417d36900a33288af587e', function (err, result) {
if (err) {}
else {
// result is true if file is removed successfully, false otherwise
console.log(result);
}
})
Remove all files from fs.files collection:
gfsEasy.removeAll(function (err, result) {
if (err) {}
else {
// result is 'All files deleted successfully' if all files are removed successfully
console.log(result);
}
})
Store a file in the fs.files collection. Here ng-file-upload is used on the client side to send the file to the server (some tips are provided here).
Don't forget to use connect-multiparty as a middleware:
pictureRouter.route('/putFile')
.post(multipartMiddleware, function (req, res, next) {
gfsEasy.putFile(req.files.file.path,
req.files.file.name,
function (err, file) {
if (err) next(err);
res.json(file);
})
});
Your document must have two fields : imgId and imgBase64.
Take this for instance. The document of a user:
{
"_id" : ObjectId("59a9c78d7d8818260ccd753c"),
"name" : "kasra",
"age" : 22,
"address": "some address",
"imgId" : ObjectId("5ab4260c26c6441d946b69e4"),
"imgBase64" : "empty"
}
The document of a picture: ( Remember that all of your pictures are stored in fs.files collection. )
{
"_id": "5ab4260c26c6441d946b69e4",
"filename": "user1.png",
"contentType": "binary/octet-stream",
"length": 43630,
"chunkSize": 261120,
"uploadDate": "2018-03-22T21:54:20.937Z",
"aliases": null,
"metadata": null,
"md5": "2830695ace2df8a15d3479c432af9f88"
}
Your document (in our example the user document) must hold the id of the picture under the imgId field
Once the populateImage function is called with the user document as the first parameter, the imgBase64 field will be populated with the base64 format of the corresponding picture and the updated user document will be available in the callback function:
The updatedUserDoc:
{
"_id" : ObjectId("59a9c78d7d8818260ccd753c"),
"name" : "kasra",
"age" : 22,
"address": "some address",
"imgId" : ObjectId("5ab4260c26c6441d946b69e4"),
"imgBase64" : "data:image/png;base64,iVBORw0KGgoA..." <------
}
The sample code :
userRouter.route('/user')
.get(function (req, res, next) {
gfsEasy.populateImage(userDoc, function (err, updatedUserDoc) {
if (err) {}
else {
res.json(updatedUserDoc);
}
});
});
Populate imgBase64 field in documents in the given array:
userRouter.route('/user')
.get(function (req, res, next) {
gfsEasy.populateImages(userDocArray, function (err, updatedUserDocArray) {
if (err) {}
else {
res.json(updatedUserDocArray);
}
});
});
As mentioned above, you can use ng-file-upload to upload your files:
We've created two buttons, one for choosing a file and the other for submitting:
HTML:
<form name="Subform">
<div class="button btn btn-success" ngf-select ng-model="file" name="file" ngf-pattern="'*/*'"
ngf-accept="'*/*'" ngf-max-size="20MB" ngf-min-height="100">Select
</div>
<button class="btn btn-info" type="submit" ng-click="submit()">putFile</button>
</form>
Assume that the controller below controls the form in our view:
Controller:
$scope.submit = function () {
fileUpload.uploadFile($scope.file);
};
We have created a function which receives the file and uploads it using Upload (ng-file-upload) to the server. Please visit ng-file-upload.
fileUpload Service:
this.uploadFile = function (file) {
Upload.upload({
url: 'http://localhost:3000/gfs/putFile',
data: {file: file}
}).then(function (resp) {
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
MIT © Kasra Ghasemi