gpt4 book ai didi

node.js - 在 MongoDB/NodeJs/GridFS 堆栈中从 GridFS 下载文件时出现问题

转载 作者:可可西里 更新时间:2023-11-01 09:15:11 25 4
gpt4 key购买 nike

我正在开发 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 文件对其进行测试。

关于node.js - 在 MongoDB/NodeJs/GridFS 堆栈中从 GridFS 下载文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com