2017-08-14 126 views
1

我有一個真的很難的時間解決這個問題。我嘗試了很多不同的解決方案,我不知道現在需要修復的地方。我嘗試通過http獲取Blob並使用FileSaver.js爲用戶下載文件。由於某種原因,每次我嘗試打開圖像時,都會收到「已損壞,已損壞或過大」消息。我試圖玩'responseType'(改爲'blob'),在頭上添加一個'Accept'。沒有什麼似乎爲我工作!使用AngularJS和Angular-FileSaver.js下載Blob通過http

有人可能會指出我在正確的方向嗎?

服務

download: function(blobId, token) { 
    var req = { 
    method: 'GET', 
    cache: false, 
    url: 'api/Blob/DownloadBlob/' + blobId, 
    headers: { 
    'responseType': 'arraybuffer', 
    'Authorization': token 
    } 
    }; 

    return $http(req) 
    .then(function (response) { 
     return response; 
    }, function(response) { 
     // something went wrong 
     return $q.reject(response.data); 
    }); 
} 

控制器

$scope.downloadFile = function() { 
    Data.download($scope.blobId, $scope.token).then(function (response) { 
    var blob = new Blob([response], { type: 'image/png' }); 
    FileSaver.saveAs(blob, 'download.png'); 
    }); 
}; 
+1

'responseType'是** **不是一個頭。請參閱https://docs.angularjs.org/api/ng/service/$http#usage – Phil

+1

FileSaver不適用於Safari或iOS Safari瀏覽器。我相信它應該可以在Mac上的Safari 10.1上運行,因爲該版本表示它支持anchor標記中的下載屬性(文件引擎使用什麼文件) – Patrick

回答

2

前兩個問題,我可以看到的是...

  1. responseType配置屬性不應在headers對象
  2. 您正在將response對象傳遞給Blob構造函數,您可能想要通過response.data

我與

return $http.get('api/Blob/DownloadBlob/' + blobId, { 
    responseType: 'blob', 
    headers: { 
    Authorization: token 
    }, 
    transformResponse: function(data) { 
    return data // there's no need to attempt any transformations 
    } 
}).then(function(response) { 
    return response.data // your provider consumers only need the blob data 
}) 

,並在你的消費者去...

Data.download($scope.blobId, $scope.token).then(function(blob) { 
    FileSaver.saveAs(blob, 'download.png') 
}) 
+1

FileSaver不適用於Safari或iOS Safari瀏覽器。我相信它應該在Mac上的Safari 10.1中工作,因爲該版本表示它支持錨標記中的下載屬性(文件引擎使用哪個文件管理器)。 – Patrick

+0

@Patrick我建議你在上面的問題中添加你的評論,這樣Nick就能看到它。他是使用FileSaver的人,而不是我 – Phil

+0

我投票答案也是如此。我也在使用FileSaver,所以如果他需要支持這些瀏覽器,就要確保知道這些限制。 – Patrick