【问题标题】:Angular is blocking file downloadAngular 正在阻止文件下载
【发布时间】:2017-02-03 05:01:53
【问题描述】:

当我针对 webapi 控制器发起 get 角度请求时,该控制器以 HttpResponseMessage 中包装的文件进行响应,浏览器无法识别这是文件下载并且数据丢失。

我检查了提琴手,我可以看到响应中存在二进制数据。

我用这个来发起获取请求:

      return $http.get(serviceURLRoot + 'api/myreport/' + dateParams.StartDate + '/' + dateParams.EndDate, { withCredentials: true }).success(function (data) {
      });

如果我直接在地址栏中输入请求,我会很好地恢复文件。使用window.open 也可以:

window.open(serviceURLRoot + 'api/rawdatareport/' + dateParams.StartDate + '/' + dateParams.EndDate);

为什么$http.get 不起作用?

编辑-----

这是构建在服务器上的 HttpResponseMessage:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(pck.GetAsByteArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
    FileName = "myReport.xlsx"
};

return result;

【问题讨论】:

  • 你对响应做了什么? Ajax 本身不会初始化文件保存对话框
  • @charlietfl 我不确定您的意思是在服务器上还是在客户端上。我已经更新了问题以显示响应是如何在服务器上构建的。在客户端,它只是显示了 return $http.get 语句,没有任何内容被忽略。

标签: javascript angularjs asp.net-web-api


【解决方案1】:

因为您正在使用 $http 执行 AJAX 请求。浏览器意识到文件即将到来的唯一方法是让浏览器去那里。意识到文件即将到来,而不是 HTML,它会弹出下载。因此,您确实必须将位置更改为该 URL 或在该 URL 中打开一个新窗口。

【讨论】:

猜你喜欢
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多