I am using NodeJs 1.9.x with express 3.x, mongoose 3.3.x and gridfs-stream modules. Following is upload code. Which is working great.
var mongoose = require('mongoose');
var fs = require('fs');
var GridStrm = require('gridfs-stream');
exports.stream_ajax_upload_file = function(req, res){
var fileType = req.header('X-File-Type');
var fileName = req.header('X-File-Name');
var uniqId = req.param('uniqId', '112211112111');
var conn = mongoose.createConnection('localhost', 'TestArun', 27017);
conn.once('open', function () {
var gfs = GridStrm(conn.db, mongoose.mongo);
var fileId = new ObjectID(uniqId);
writestream = gfs.createWriteStream(fileId, [{"content_type": fileType, "metadata":{ "fileName": fileName, "uploaded_at": (new Date()).toString() }}]);
req.on('data', function(data) {
console.log("Writing stream in to gridfs");
writestream.write(data);
});
req.on('end', function(data) {
writestream.end();
res.send("I think it is uoploaded: ID::" + uniqId);
});
});
}
I am able to see the uploaded data in as chunks in gridfs. Following is the download code.
var mongoose = require('mongoose');
var fs = require('fs');
var GridStrm = require('gridfs-stream');
exports.download_file_as_stream = function(req, res){
var uniqId = req.param('uniqId', '112211112111');
var conn = mongoose.createConnection('localhost', 'TestArun', 27017);
conn.once('open', function () {
var gfs = GridStrm(conn.db, mongoose.mongo);
var fileId = new ObjectID(uniqId);
var readstream = gfs.createReadStream(fileId, [{"content_type": 'application/pdf'}]);
//res.header('content-type','application/pdf');
readstream.pipe(res);
});
}
The issue is I am not able to download the proper file. When I try to download I am getting some file which is downloading in the name of request url i.e: download_file_as_stream. But the size is same as the uploaded file. I think the issue with content-type, etc setting. I am not sure where is the problem. Whether it is in upload or download section ?
To make content_type
work in your writeStream, you should also pass the option mode = 'w'
. The default mode is w+, but with w+ the content_type isn't updated.
In your readStream you don't need to provide a content_type setting, since it is stored in the db!