0

我正在使用带有 express 3.x、mongoose 3.3.x 和 gridfs-stream 模块的 NodeJs 1.9.x。以下是上传代码。效果很好。

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。但大小与上传的文件相同。我认为内容类型等设置的问题。我不确定问题出在哪里。无论是在上传还是下载部分?

4

1 回答 1

0

content_type在您的 writeStream 中工作,您还应该传递 option mode = 'w'。默认模式是 w+,但使用 w+ 时 content_type 不会更新。

在您的 readStream 中,您不需要提供 content_type 设置,因为它存储在数据库中!

于 2013-04-09T06:34:42.710 回答