【问题标题】:Downloading Blob via http using AngularJS and Angular-FileSaver.js [duplicate]使用 AngularJS 和 Angular-FileSaver.js 通过 http 下载 Blob [重复]
【发布时间】:2017-08-15 08:13:03
【问题描述】:

解决这个问题我真的很难。我已经尝试了很多不同的解决方案,以至于我不确定现在需要修复哪里。我正在尝试通过 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');
  });
};

【问题讨论】:

  • responseType 不是标题。见docs.angularjs.org/api/ng/service/$http#usage
  • FileSaver 不适用于 Safari 或 iOS Safari 浏览器。我相信它应该可以在 Mac 上的 Safari 10.1 中运行,因为该版本表示它支持锚标记中的下载属性(文件保护程序在后台使用什么)

标签: angularjs filesaver.js


【解决方案1】:

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

  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')
})

【讨论】:

  • FileSaver 不适用于 Safari 或 iOS Safari 浏览器。我相信它应该可以在 Mac 上的 Safari 10.1 中运行,因为该版本表示它支持锚标记中的下载属性(文件保护程序在后台使用什么)。
  • @Patrick 我建议您将您的评论添加到上面的问题中,以便尼克可以看到它。他是使用 FileSaver 的人,而不是我
  • 我也对答案投了赞成票。我也在使用 FileSaver,所以如果他需要支持这些浏览器,我想确保知道这些限制。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
相关资源
最近更新 更多