【发布时间】:2017-10-26 06:32:29
【问题描述】:
我从服务器端获取的 POST 请求的 HTTP 响应是一个 xlsx 文件。如何在 angularjs 1 中下载该文件?
注意:res.download() 在这里不起作用,因为它是我正在发出的 POST 请求,而 res.download() 仅适用于 GET请求
【问题讨论】:
我从服务器端获取的 POST 请求的 HTTP 响应是一个 xlsx 文件。如何在 angularjs 1 中下载该文件?
注意:res.download() 在这里不起作用,因为它是我正在发出的 POST 请求,而 res.download() 仅适用于 GET请求
【问题讨论】:
以下将起作用:
$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})
.success(function (data,status,headers) {
var blob = new Blob([data]);
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = objectUrl;
a.download = headers().filename;
a.click();
console.log("Report downloaded");
}).error(function (err) {
console.log(err);
});
【讨论】:
您可以直接在Client Side 上进行,您可能会遇到一些跨浏览器兼容性问题(最好的方法始终是通过服务器提供下载流,例如对于大文件)。
// this example uses a JSON String
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
['something', 'to', 'download'], null, 2
)];
const downloader = document.createElement('a');
// set the filename here
downloader.download = 'filename.json';
const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);
// trigger the download
downloader.click();
在我看来,重定向到可下载资源可能是最佳选择。
【讨论】: