如何使用 Angular 的 2+ @angular/http 模块接收 blob 响应?
How to receive blob responses using Angular's 2+ @angular/http module?
我正在尝试从 angular 2 应用程序中提供 pdf 下载...
此代码有效:
var reportPost = 'variable=lsdkjf';
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/a2/pdf.php", true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([this.response], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
}
}
xhr.send(reportPost);
但我更愿意使用 angular 2 的内置 Http 客户端。
一点研究:
- angular 文档在发布时未写入:
https://angular.io/docs/js/latest/api/http/ResponseTypes-enum.html
- 不确定这是否适用,但 rxjs responseType 参数似乎
仅包含文本和 json:
https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md
和一些测试代码:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/a2/pdf.php', reportPost, {
headers: headers
})
.retry(3)
// .map( (res:any) => res.blob() ) // errors out
.subscribe(
(dataReceived:any) => {
var blob = new Blob([dataReceived._body], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
},
(err:any) => this.logError(err),
() => console.log('Complete')
);
ps。 saveAs 函数来自这里:https://github.com/eligrey/FileSaver.js
随着 Angular2 final 的发布,我们可以定义一个服务:
@Injectable()
export class AngularService {
constructor(private http: Http) {}
download(model: MyModel) { //get file from service
this.http.post("http://localhost/a2/pdf.php", JSON.stringify(model), {
method: RequestMethod.Post,
responseType: ResponseContentType.Blob,
headers: new Headers({'Content-Type', 'application/x-www-form-urlencoded'})
}).subscribe(
response => { // download file
var blob = new Blob([response.blob()], {type: 'application/pdf'});
var filename = 'file.pdf';
saveAs(blob, filename);
},
error => {
console.error(`Error: ${error.message}`);
}
);
}
}
此服务将获取文件,然后将其提供给用户。
zip 文件示例:
使用 @4.3, @5
和 HttpClientModule,我最终做了:
this.http.post(`${environment.server}/my/download`,
data,
{responseType: 'blob', observe: 'response'})
.map( res => ({content: res.body,
fileName: res.headers.get('content-filename')}));
看这里:
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
我正在尝试从 angular 2 应用程序中提供 pdf 下载...
此代码有效:
var reportPost = 'variable=lsdkjf';
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/a2/pdf.php", true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([this.response], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
}
}
xhr.send(reportPost);
但我更愿意使用 angular 2 的内置 Http 客户端。
一点研究:
- angular 文档在发布时未写入: https://angular.io/docs/js/latest/api/http/ResponseTypes-enum.html
- 不确定这是否适用,但 rxjs responseType 参数似乎 仅包含文本和 json: https://github.com/Reactive-Extensions/RxJS-DOM/blob/master/doc/operators/ajax.md
和一些测试代码:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/a2/pdf.php', reportPost, {
headers: headers
})
.retry(3)
// .map( (res:any) => res.blob() ) // errors out
.subscribe(
(dataReceived:any) => {
var blob = new Blob([dataReceived._body], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
},
(err:any) => this.logError(err),
() => console.log('Complete')
);
ps。 saveAs 函数来自这里:https://github.com/eligrey/FileSaver.js
随着 Angular2 final 的发布,我们可以定义一个服务:
@Injectable()
export class AngularService {
constructor(private http: Http) {}
download(model: MyModel) { //get file from service
this.http.post("http://localhost/a2/pdf.php", JSON.stringify(model), {
method: RequestMethod.Post,
responseType: ResponseContentType.Blob,
headers: new Headers({'Content-Type', 'application/x-www-form-urlencoded'})
}).subscribe(
response => { // download file
var blob = new Blob([response.blob()], {type: 'application/pdf'});
var filename = 'file.pdf';
saveAs(blob, filename);
},
error => {
console.error(`Error: ${error.message}`);
}
);
}
}
此服务将获取文件,然后将其提供给用户。
zip 文件示例:
使用 @4.3, @5
和 HttpClientModule,我最终做了:
this.http.post(`${environment.server}/my/download`,
data,
{responseType: 'blob', observe: 'response'})
.map( res => ({content: res.body,
fileName: res.headers.get('content-filename')}));
看这里:
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})