2015-11-02 85 views
1

我正在爲我構建的服務器基於Angular.js的查看器工作,試圖添加「執行&下載」按鈕。如何通過angular.js下載從HTTP返回的二進制文件:POST請求?

我送執行什麼請求的方式是通過HTTP:POST請求,與頭:

"Accept" = "application/zip" 
"X-MyApp-URI = "path/to/my/file/that/the/server/can/access/to" 

服務器這種要求的respons基本上是:

X-Powered-By: Servlet/3.0 
Content-Type: application/zip 
Access-Control-Allow-Credentials: true 
Access-Control-Allow-Headers: Content-Type, Content-Disposition, Accept, Authorization, X-..... 
Access-Control-Allow-Methods: GET, POST 
Access-Control-Allow-Origin: * 
Content-Disposition: inline; filename="result.zip" 
Transfer-Encoding: chunked 
Date: Mon, 02 Nov 2015 15:29:42 GMT 

我已經用RESTClient 3.4 &郵差應用試過了這個執行過程,在這兩種情況下,下載的結果文件都是我發送的正確的zip文件。

這裏是我想通過我的網絡應用程序來執行代碼:

var config = {'Accept':'application/zip', 'X-MyApp-URI' = 'path..'}; 
$http.post("../serverPath",{responseType: "bufferArray"}, config) 
    .success(function (response) { 
     var bytes = new Array(response.length); 
     for (var i = 0; i < response.length; i++) { 
      bytes[i] = response.charCodeAt(i) 
     } 
     var bytesUint = new Uint8Array(bytes); 
     var blob = new Blob(bytesUint, {type: 'application/zip'}); 
     var blobUrl = URL.createObjectURL(blob); 
     var a = document.createElement("a"); 
     document.body.appendChild(a); 
     a.href = blobUrl; 
     a.download = 'result.zip'; 
     a.click(); 
}); 

不幸的是,我已經試過的參數我能在網上找到幾乎所有的組合,並沒有什麼幫助,通過上面的blob下載的文件總是被損壞。

我可以使用的解決方案是圍繞純JS代碼,jQuery或特定的Angular.JS &任何Apache已經開發的插件,可能有助於解決這個問題。

回答

0

嘗試直接傳遞Uint8ArrayBlob如下:

var config = {'Accept':'application/zip', 'X-MyApp-URI' = 'path..'}; 
$http.post("../serverPath",{responseType: "bufferArray"}, config) 
    .success(function (response) { 
     var bytesUint = new Uint8Array(response); 
     var blob = new Blob([bytesUint], {type: 'application/zip'}); 
     var blobUrl = URL.createObjectURL(blob); 
     var a = document.createElement("a"); 
     document.body.appendChild(a); 
     a.href = blobUrl; 
     a.download = 'result.zip'; 
     a.click(); 
}); 
相關問題