在MongoDB / NodeJs / GridFS堆栈中从GridFS下载文件的问题
我正在使用NodeJs API,并select使用GridFS来存储和下载文件。 我有两个API的这个问题:上传和下载。 当我用邮递员给他们打电话时,这两个API都是完美的; 但是我有一个问题使用浏览器下载文件。 看起来浏览器看到的是200个HTTP代码,并且期望文件在内容仍然stream式传输时立即在那里。 因此,它抱怨图像或PDF等有错误或格式无效。 唯一正在工作的文件types是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 >
任何想法如何解决这个问题?
听起来像这个问题是与MIMEtypes。 添加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文件进行testing。