node.js - 使用 loopback / express.js 下载文件
问题描述
这是远程功能:
Document.download = async (id, res) => {
try {
const document = await Document.findById(id)
res.set('Content-Type','application/octet-stream');
res.set('Content-Type','application/download');
res.set('Content-Transfer-Encoding','binary');
const fileData = await readFile(document.path, { encoding: 'binary' })
res.send(fileData);
} catch (e) {
console.log(e)
}
}
以及这个远程方法的配置
Document.remoteMethod(
'download',
{
http: {path: '/:id/download', verb: 'get'},
accepts: [
{ arg: 'id', type: 'string', required: true },
{ arg: 'res', type: 'object', 'http': { source: 'res' } }
],
returns: [
{ arg: 'body', type: 'file', root: true }
]
}
)
如果我尝试下载一个 txt 文件,它会按预期工作。下载的文件大小正确。但是,如果我尝试对 PDF 进行相同操作,则会得到一个空文件,其大小不正确(更大)。
在客户端,我有以下下载代码
$.ajax(url, {cache: false}).success(function (data) {
let blob = new Blob([data], {type: row.get('mimetype')});
saveAs(blob, 'foo');
});
解决方案
我认为可以只发送res.download(path-to-file)
这是我的示例代码
app.get('/download/template-tenant', function(req, res) {
const file = 'template/test.pdf';
res.download(file);
});
推荐阅读
- python - 将大文件(ML/AI 模型)从本地服务器传输到 aws 的正确方法是什么?
- javascript - React className 条件逻辑块从发生过渡,不知道为什么
- facebook - 如何在 Facebook 上找到拥有超过一定数量关注者的粉丝页面?
- android - 微调器下拉列表显示在微调器小部件下方
- rxjs - RxJS 中是否有类似 flatTap 的东西
- sql - SQL - 通过条件选择的键获取唯一值
- python - 按日期分组并添加具有最小值的新列 - 熊猫
- python - 为什么在for循环的每一步都分配给l
- npm - 为什么 npm 安装包会创建一个指向父目录的节点模块?
- maven-surefire-plugin - 如何通过命令行传递 maven-surefire-plugin 参数