2016-03-07 72 views
4

我正在嘗試製作簡單的文件服務器。我有Node.js後端和MongoDB GridFS存儲來存儲文件。我通過gridfs-stream從服務器獲取文件。在前端我使用Angular。我有兩個主要問題:通過角度下載文件

  1. 當我使用的Blob服務下載,filename變成了: 「d1c393df-b0d9-4ae5-BEFE-8d45b183eb54 ......」 之類的。我讀了很多關於它的文檔,但沒有找到任何解決方案。
  2. 當我只通過Express下載服務而沒有身份驗證時,文件會正確加載。但我通過Angular發送授權信息,如果沒有它們,應用程序會拋出錯誤。我可以指定沒有身份驗證的路由,但這會使我的應用程序不安全。

我希望你能幫我:

  1. 找到另一種方式來下載任何格式的文件。
  2. 將我現有的代碼,把事情正常工作

我的角度服務通過構建一個斑點獲得的文件:

getFilesFactory.download = function(filename){ 
    $http.get('/api/files/' + filename, {responseType:'arraybuffer'}) 
    .then(function(data){ 
    var stringCT = data.headers('Content-Type').toString(); 
    console.log(stringCT); 
    var contentType = stringCT.substring(1, stringCT.length - 1); 
    console.log(contentType); 

     switch (contentType) { 
     case "image/jpeg": 
      file = new Blob([data.data], {type: 'image/jpeg'}); 
      fileURL = URL.createObjectURL(file); 
      $window.open(fileURL); 
     break; 
     case "application/pdf": 
      file = new Blob([data.data], {type: 'application/pdf'}); 
      fileURL = URL.createObjectURL(file); 
      $window.open(fileURL); 
     break; 
     case "application/msword": 
      file = new Blob([data.data], {type: 'application/msword'}); 
      fileURL = URL.createObjectURL(file); 
      $window.open(fileURL); 
     break; 
     case "application/octet-stream": 
      file = new Blob([data.data], {type: 'application/octet-stream'}); 
      fileURL = URL.createObjectURL(file); 
      $window.open(fileURL); 
     break; 
     default: console.log("no contentType match"); 
     } 
    }); 
}; 

回答

0

你並不需要使用ajax下載文件並打開它在使用$window.open(fileURL);。您可以使用'/api/files/' + filename網址打開新窗口,瀏覽器將開始下載內容。您可以控制服務器端的Content-Type和文件名。你可以看看例子:Nodejs send file in response

+0

我使用這種技術時,沒有Angular服務應用程序。但是當我實現它時,Express方法'res.redirect()'不工作(瀏覽器不打開任何鏈接,並且我的數據丟失了) 您能否提供示例? – stasinua