【发布时间】:2018-11-17 04:47:29
【问题描述】:
我有一些 Excel 文档 (xlsx) 以二进制形式保存在 MongoDB 中。当用户导航到 url 并提供文件供用户下载时,我希望 node.js 从数据库中检索文件。我已成功下载 a 文件,但在尝试打开文件时出现 Excel 错误:
“Excel 无法打开文件 '5beec8ef3cf3e70b5ce8972e.xlsx',因为文件格式或文件扩展名无效。请确认文件未损坏并且文件扩展名与文件格式匹配。”
该文件也以 0 字节保存。我认为在尝试创建缓冲区之前我没有正确转换来自 MongoDB 的数据。这是我的脚本:
app.get('//downloadReport/:id', (req, res) => {
dbo = db.db('test');
dbo.collection("reports").findOne(
{'_id': mongodb.ObjectId(req.params.id)}
).then(doc => {
console.log('type of doc.file: ' + typeof doc.file);
// returns:
// type of doc.file: object
console.log(doc.file);
// returns:
// Binary {
// _bsontype: 'Binary',
// sub_type: 0,
// position: 1146504,
// buffer: <Buffer 50 4b 03 04 14 00 00 00 08 00 12 66 6f 4d f8 64 19 ... > }
res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);
// This one doesn't work
// res.end(doc.file, 'binary');
// returns:
// TypeError: First argument must be a string or Buffer
res.end(new Buffer(doc.file, 'binary') );
});
});
我尝试向下钻取到 doc.file.Binary.buffer,但我收到一条错误消息,提示 doc.file.Binary 未定义。
我还希望使用正确的文件名下载文件。我已经尝试将此添加到 writeHead:
['Content-disposition', 'filename=' + doc.filename]
但我在 Chrome 中遇到错误:ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
有人知道如何进行这项工作吗?提前致谢!
【问题讨论】: