2016-03-15 125 views
1

下面的代碼下載一個文件,無法打開(損壞),我完全不知道爲什麼。我已經在很多方面嘗試了這一點,但它永遠不會工作,它總是會產生一個損壞的文件。原始文件不是問題,因爲它可以正常打開。我正在嘗試打開mp4,mp3和圖像文件。Javascript Blob anchortag下載產生損壞的文件

//$scope.fileContents是一個字符串

$scope.fileContents = $scope.fileContents.join(","); 
     var blob = new Blob([$scope.fileContents], {type: $scope.file.fileDetails.type}); 
     var dlURL = window.URL.createObjectURL(blob); 
     document.getElementById("downloadFile").href = dlURL; 
     document.getElementById("downloadFile").download = $scope.file.fileDetails.name; 
     document.getElementById("downloadFile").click(); 
     window.URL.revokeObjectURL(dlURL); 
+0

'$ scope.fileContents是string'這就是問題所在。它需要是二進制的。 – Musa

回答

2

您需要使用ArrayBuffer例如下載的文件內容爲二進制

$http.get(yourFileUrl, { responseType: 'arraybuffer' }) 
    .then(function (response) { 
     var blob = new Blob([response.data], {type: $scope.file.fileDetails.type}); 
     // etc... 
    }); 


來源:

+0

您節省了我的時間 –

+1

如果字節數組來自數據庫會怎麼樣?我面臨同樣的問題,但在我的情況下,字節數組是直接從數據庫傳遞給JavaScript函數 – Soumya