Store file in Mongo GridFS using ExpressJS after boot

I started creating REST api using expressJS. I am new to node, so please bear with me. I want users to be able to upload a file directly to Mongo GridFS using the message for the / upload route.

From what I understand in the expressJS documentation, the req.files.image object is available on the route after loading, which also includes the path and filename attribute. But how can I accurately read image data and save it to GridFS?

I looked at gridfs-stream , but I cannot tie the ends together. Should I read the file first and then use this data for the writestream channel? Or can I just use the file object from the expression and use these attributes to create a write stream? Any pointers would be appreciated!

+7
source share
1 answer

Here is a simple demo:

var express = require('express'); var fs = require('fs'); var mongo = require('mongodb'); var Grid = require('gridfs-stream'); var db = new mongo.Db('test', new mongo.Server("127.0.0.1", 27017), { safe : false }); db.open(function (err) { if (err) { throw err; } var gfs = Grid(db, mongo); var app = express(); app.use(express.bodyParser()); app.post('/upload', function(req, res) { var tempfile = req.files.filename.path; var origname = req.files.filename.name; var writestream = gfs.createWriteStream({ filename: origname }); // open a stream to the temporary file created by Express... fs.createReadStream(tempfile) .on('end', function() { res.send('OK'); }) .on('error', function() { res.send('ERR'); }) // and pipe it to gfs .pipe(writestream); }); app.get('/download', function(req, res) { // TODO: set proper mime type + filename, handle errors, etc... gfs // create a read stream from gfs... .createReadStream({ filename: req.param('filename') }) // and pipe it to Express' response .pipe(res); }); app.listen(3012); }); 

I use httpie to download the file:

 http --form post localhost:3012/upload filename@ ~/Desktop/test.png 

You can check your database if the file is uploaded:

 $ mongofiles list -d test connected to: 127.0.0.1 test.png 5520 

You can also download it again:

 http --download get localhost:3012/download?filename=test.png 
+29
source

All Articles