2016-10-03 45 views
0

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

customer.downloadFile = function downloadFile(userId, 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} 
        ], 
      returns: [ 
       { arg: 'body', type: 'file', root: true }, 
       { arg: 'Content-Type', type: 'string', http: { target: 'header' } } 
      ], 
      http: {path: '/:id/downloadFile', verb: 'get'} 
     } 
    ); 

与上面的代码的问题是,浏览器虽然显示美丽的pdf文件容器,但不是文件下面的错误显示:

enter image description here

请指出至于代码有什么问题以及如何纠正。 从这个URL得到了领导:https://github.com/strongloop/loopback-swagger/issues/34

+0

内容处置:内联; filename =“filename.pdf”//进入头文件 – MMK

回答

0

明白了与以下工作:

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

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

其中'res'定义在哪里? – user3568719

1

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

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

它是如何做:

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

就是这样一个storage数据源。您可以上传和下载文件到您的容器。 使用容器,您可以将文件存储到本地文件系统,或稍后再移动到云解决方案。