无法从MongoDB GridFS下载文件作为nodejs / expressjs的流

时间:2012-11-22 06:55:17

标签: node.js mongodb stream express gridfs

我使用NodeJs 1.9.x和express 3.x,mongoose 3.3.x和gridfs-stream模块。以下是上传代码。哪个工作得很好。

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);
        });
    });

}

我能够在gridfs中以块的形式看到上传的数据。以下是下载代码。

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);
    }); 
}

问题是我无法下载正确的文件。当我尝试下载时,我收到一些以请求URL 即:download_file_as_stream 的名义下载的文件。但是大小与上传的文件相同。我认为内容类型等设置的问题。我不确定问题出在哪里。是上传还是下载?

1 个答案:

答案 0 :(得分:0)

要使content_type在您的writeStream中运行,您还应该传递选项mode = 'w'。默认模式是w +,但是使用w +时,content_type不会更新。

在readStream中,您不需要提供content_type设置,因为它存储在db中!