首页 > 解决方案 > 使用 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');
        });

这是我尝试下载 PDF 时的响应截图。(页数是正确的,但它们是空白的) 在此处输入图像描述

标签: node.jsdownloadloopbackjs

解决方案


我认为可以只发送res.download(path-to-file)

这是我的示例代码

app.get('/download/template-tenant', function(req, res) {
    const file = 'template/test.pdf';
    res.download(file);
});

推荐阅读