2016-10-03 91 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數據源。您可以上傳和下載文件到您的容器。 使用容器,您可以將文件存儲到本地文件系統,或稍後再移動到雲解決方案。