angular2下载文件与post请求 [英] angular2 download file with post request
问题描述
我有一个按钮定义为:
<button pButton type="button" label="Download" data-icon="fa-cloud-download" (click)="download()"></button>
其中下载
方法委托给服务,并且服务使用post方法调用api:
where the download
method delegates to a service, and the service call the api with a post method:
download(model:GlobalModel) {
let downloadURL = base + "rest/process/download";
let body = JSON.stringify(model);
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
this.http.post('http://localhost:48080/rest/process/download', body, options)
.toPromise()
.then(
response => {
console.log(response);
var mediaType = 'application/zip';
var blob = new Blob([response.blob()], {type: mediaType});
var filename = 'project.zip';
saveAs(blob, filename);//FileSaver.js libray
});
}
但是现在,$ code> blob )方法尚未实现,还有使用 _body
的其他答案,但是有一个类似于_body is private的类似脚本错误。
But by now the blob()
method has not been implemented and there are other answers using _body
but there is an typescript error like "_body is private".
浏览器显示下载窗口,但是当我下载文件已损坏,无法打开时(我查看 postman
和文件从服务器生成OK)
The browser displays the download window, but when I download the file is corrupted and cannot open it (I check with postman
and the file is generated OK from the server).
如何正确下载文件?如果不可能,可以使用解决方法?
How could I download a file properly?... if not possible, There is available a workaround?
推荐答案
我终于解决了使用答案中解释的技巧: https://stackoverflow.com/a/37051365/2011421
I finally solved using the trick explained in the answer: https://stackoverflow.com/a/37051365/2011421
我在这里介绍我的具体方法,以防万一:
Here I describe here my particular approach just in case:
download(model:GlobalModel) {
// Xhr creates new context so we need to create reference to this
let self = this;
var pending:boolean = true;
// Create the Xhr request object
let xhr = new XMLHttpRequest();
let url = BASE + "/download";
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.responseType = 'blob';
// Xhr callback when we get a result back
// We are not using arrow function because we need the 'this' context
xhr.onreadystatechange = function () {
// We use setTimeout to trigger change detection in Zones
setTimeout(() => {
pending = false;
}, 0);
// If we get an HTTP status OK (200), save the file using fileSaver
if (xhr.readyState === 4 && xhr.status === 200) {
var blob = new Blob([this.response], {type: 'application/zip'});
saveAs(blob, 'project.zip');
}
};
// Start the Ajax request
xhr.send(JSON.stringify(model));
}
不幸的是,角度2 http
现在的对象还不完整,而且这个解决方案虽然有用,但感觉很糟糕。
Unfortunately angular2 http
object by now is not complete and this solution although useful feels hacky.
这篇关于angular2下载文件与post请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!