Stored files directly in mongodb using gridfs-stream

I need to save some files like: images, video, pdf ... in mongodb, so I am using gridfs-stream and express.js

var file = req.files.file; 
req.pipe(gfs.createWriteStream({
    filename:file.originalname,
    mode:"w",
    chunkSize:1024*4,
    content_type:file.mimetype,
    root:"fs"
})
res.send(200);

      

for testing i am using postman and set the POST request like this:

 POST /fs/upload HTTP/1.1
 Host: localhost:5000
 Cache-Control: no-cache

 ----WebKitFormBoundaryE19zNvXGzXaLvS5C
 Content-Disposition: form-data; name="file"; filename="epic.png"
 Content-Type: image/png


  ----WebKitFormBoundaryE19zNvXGzXaLvS5C

      

the problem is that in this way just save the file data:

{
    "_id" : ObjectId("54d14ec5b102fe401519a3c1"),
    "filename" : "epic.png",
    "contentType" : "image/png",
    "length" : 0,
    "chunkSize" : 4096,
    "uploadDate" : ISODate("2015-02-03T22:42:14.730Z"),
    "aliases" : null,
    "metadata" : null,
    "md5" : "993fb9ce262a96a81c79a38106147e95"
}

      

but not content i mean binary data for it, in mongodb it is storage for which the proforma length is 0, bacause has no chunks in fs.chucks.

0


source to share


1 answer


A blog reading discovered a response to streaming data directly in the database using express.js, gridfs-stream.js and multer middleware like this:

var multer = require('multer');

app.post('/fs/upload', multer({
    upload: null,// take uploading process 

    onFileUploadStart: function (file) {
        //set upload with WritableStream        
        this.upload = gfs.createWriteStream({
            filename: file.originalname,
            mode: "w",
            chunkSize: 1024*4,
            content_type: file.mimetype,
            root: "fs"
        });
     },

     onFileUploadData: function (file, data) {
        //put the chucks into db 
        this.upload.write(data);
     },

     onFileUploadComplete: function (file) {
        //end process 
        this.upload.on('drain', function () {
            this.upload.end();
        });
     }
}), function (req, res) {
   res.sendStatus(200);
});

      



For testing:

app.route('/fs/download/:file').get(function (req, res) {
   var readstream = gfs.createReadStream({_id: req.params.file});
   readstream.pipe(res);
});

      

+2


source







All Articles