2017-09-01 95 views
1

我的工作在我的前端是AngularJS和後端彈簧控制器文件下載:春天 - AngularJS

downloadResponse.success(function(response){ 
        console.log(JSON.stringify(response)); 

        var file = new Blob([ response ], { 
         type : 'application/octet-stream', 
        }); 
        var fileURL = URL.createObjectURL(file); 
        var a   = document.createElement('a'); 
        a.href  = fileURL; 
        a.target  = '_blank'; 
        a.download = fileName; 
        document.body.appendChild(a); 
        a.click(); 
       }).error(function(response){ 
        console.log("Error"); 
       }); 
      }; 

呼叫到春節控制器

downloadFile:function(loggedId, fileId, fileName){ 
      var downloadFileURL = "/downloadFile"; 
      var formData = $.param({ "loggedId" : loggedId, "fileId" : fileId, "fileName": fileName}); 

      return $http.post(downloadFileURL,formData, {headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}}, {responseType:"arraybuffer"}); 
     } 

春季控制器

文件下載
@RequestMapping(value = "/downloadFile") 
public void downloadFile(@RequestBody String msgBody, @RequestParam(value = "loggedId") String loggedId, @RequestParam(value = "fileId") String fileId, @RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws Exception {  
    byte[] bytes = downloadFile(loggedId, fileId, fileName, request, response); 
    response.setContentType("application/octet-stream; charset=UTF-8"); 
    response.setContentLength(bytes.length); 
    response.getOutputStream().write(bytes); 

/* InputStream in = new ByteArrayInputStream(bytes); 
FileOutputStream fos = new FileOutputStream(filePath); 
IOUtils.copy(in, fos); */ ---- I am able to download the file from the Spring controller 
} 

我能夠從Spring Controller下載包含內容的文件,但面臨問題通過它角度。我得到一個空的PDF文件。文本文件正確下載。任何幫助是極大的讚賞。

編輯1:我可以看到像這樣在瀏覽器中的反應,但不知道爲什麼一個空文件被創建

%PDF-1.4 
%���� 
612 0 obj 
<</Linearized 1 
/L 979975 
/H [ 10681 506 ] 
/O 614 
/E 149424 
/N 60 
/T 967590 
>> 
endobj 
    xref 
612 497 
0000000015 00000 n 
0000010395 00000 n 
0000011187 00000 n 
0000011411 00000 n 
0000011562 00000 n 
0000011779 00000 n 
0000011928 00000 n 
0000012154 00000 n 
0000n 
0000012523 00000 n 
0000012760 00000 n 
0000012941 00000 n 
0000013123 00000 n 
0000013353 00000 n 
+0

是否有任何理由爲什麼您要執行POST下載? –

+0

不,我只是在給我的彈簧控制器做一個POST請求。 – Sheetal

+0

我猜如果你改變服務器狀態,POST是有意義的。相反,它似乎只是想獲得資源.. –

回答

1

也許角不信任你的文件。請嘗試注入$ SCE(https://docs.angularjs.org/api/ng/service/ $ SCE)到您的角度控制器,然後調用

url = $sce.trustAsResourceUrl(url) 

您的網址你寫它變成a.href之前。

而且我認爲PDF格式的內容在response.data中可用,而不是響應自身。

var file = new Blob(response.data, { 
    type : 'application/octet-stream', 
}); 
+0

Schuller謝謝。但是這個幫助,我仍然得到一個空文件 – Sheetal

+0

您是否將$ sce.trustAsResourceUrl(url)的響應設置爲url?我已經在上面更新了我的答案。 –

+0

好吧,我試着提到「fileURL = $ sce.trustAsResourceUrl(fileURL);」但沒有運氣 – Sheetal