使用远程方法下载 pdf

Download pdf using remote method

我打算使用远程方法下载动态生成的 pdf 文件,该文件存在于特定路径中,我正在使用 return 类型 "file"。我的实现是:

customer.downloadFile = function downloadFile(userId, res, cb){
    var reader = fs.createReadStream(__dirname + '/../document.pdf');
    cb(null, reader, 'application/pdf');
};

customer.remoteMethod(
    'downloadFile',
    {
        isStatic: true,
        accepts: [
            { arg: 'id', type: 'string', required: true },
            { arg: 'res', type: 'object', 'http': { source: 'res' } }
        ],
        returns: [
            { arg: 'body', type: 'file', root: true },
            { arg: 'Content-Type', type: 'string', http: { target: 'header' } }
        ],
        http: {path: '/:id/downloadFile', verb: 'get'}
    }
);

以上代码的问题是浏览器虽然显示了漂亮的 pdf 文件容器,但显示的不是文件,而是以下错误:

请指出代码有什么问题以及如何更正。 从这个 URL 获得线索:https://github.com/strongloop/loopback-swagger/issues/34

您应该使用 loopback-component-storage 来管理可下载文件。

文件被分组在所谓的容器中(基本上,一个文件夹只有一个层次结构,而不是更多)。

如何完成:

  1. 例如,创建一个名为 container 的模型。
  2. 创建一个 storage 数据源,用作 connector loopback-component-storage
  3. container模型数据源storage

就是这样。您可以上传和下载文件 to/from 您的容器。 使用容器,您可以将文件存储到本地文件系统,或者稍后移动到云解决方案。

得到了以下工作:

fs.readFile(fileName, function (err, fileData) {
    res.contentType("application/pdf");
    res.status(200).send(fileData);

    if (!err) {
        fs.unlink(fileName);
    }
    else {
        cb(err);
    }
});