使用AngularJS和Angular-FileSaver.js通过http下载Blob

时间:2017-08-14 23:10:07

标签: angularjs filesaver.js

我有一个真的很难解决这个问题。我尝试了很多不同的解决方案,我不确定我现在需要解决的问题。我正在尝试通过http get检索Blob并使用FileSaver.js为用户下载文件 出于某种原因,每次我尝试打开图像时,都会收到“损坏,损坏或过大”的消息。我尝试使用'responseType'(更改为'blob'),在标题中添加'Accept'。似乎没有什么对我有用!!

有人可能会指出我正确的方向吗?

服务

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 个答案:

答案 0 :(得分:2)

我能看到的前两个问题是......

  1. responseType配置属性不应位于headers对象
  2. 您正在将response对象传递给您可能希望传递Blob的{​​{1}}构造函数。
  3. 我会去

    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
    })
    
相关问题