簡體   English   中英

從MongoDB / NodeJs / GridFS堆棧中的GridFS下載文件時出現問題

[英]Issue with downloading a file from GridFS in MongoDB/NodeJs/GridFS stack

我正在研究NodeJs API,我選擇使用GridFS來存儲和下載文件。 我有兩個API用於此事:上傳和下載。 當我使用Postman調用它們時,兩種API都能正常工作; 但是我在使用瀏覽器下載文件時遇到問題。 瀏覽器似乎看到了200個HTTP代碼,並期望文件在內容仍在流式傳輸時立即出現。 因此,它抱怨圖像或PDF等有錯誤或格式無效。 唯一可用的文件類型是MP3,瀏覽器啟動MP3播放插件播放音樂。

var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var gfs = new Grid(mongoose.connection.db);
//.... some code in here
exports.download = function(req, res) {
    gfs.files.find({ "_id": mongoose.Types.ObjectId(req.params.id) }).toArray(function (err, files) {
            if(files.length===0){
            return res.status(400).send({
                message: 'File not found'
            });
            }



        var readstream = gfs.createReadStream({
              filename: files[0].filename
        });

        readstream.pipe(res);
    });
};

我使用Fiddler捕獲請求和響應:

這是請求:

GET http://localhost:9000/api/file/download/5586fd1a04de649c4eff2223?access_token=bluhbluhbluhbluhbluh HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,fa;q=0.6
Cookie: _ga=xxxxxxxxxxxxx; wp-settings-1=editor%3Dhtml%26align%3Dleft%26unfold%3D1%26mfold%3Do%26hidetb%3D1; wp-settings-time-1=1434314682; session_id=xxxxxxxxxxxxxxxxx; connect.sid=xxxxxxxxxx; token=xxxxxxxxxx

這是回應:

HTTP/1.1 200 OK
X-Powered-By: Express
content-length: 2412930
Date: Mon, 22 Jun 2015 16:45:04 GMT
Connection: keep-alive

%PDF-1.4
%    
< The rest of  PDF content comes in here >

任何想法如何解決這個問題?

聽起來問題是MIME類型。 添加node-mime模塊並嘗試以下操作:

//Get Readstream code here
var mimetype = mime.lookup(files[0].filename);

res.setHeader('Content-disposition', 'attachment; filename=' + files[0].filename);
res.setHeader('Content-type', mimetype);

readstream.pipe(res);

您還可以將mimetype設置為application/pdf以便首先使用PDF文件對其進行測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM