Angular 10文件下载



使用此功能接收数据的服务

import { RequestOptions, ResponseContentType, Http } from '@angular/http';
import { map } from 'rxjs/operators';
constructor(private http: Http) { }
downloadFile(id): Observable<Blob> {
let options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get(this.baseUrl + `coursepurchased/receipt/` + bookingId, options)
.pipe(map(res => res.blob()))
}

组件使用"文件保护程序"解析blob

import {saveAs as importedSaveAs} from "file-saver";
getCourseReceipt(bookingId) {
this.studentInfoService.getCourseInvoice(bookingId).subscribe(
blob => {
var fileName = 'test.pdf';
importedSaveAs(blob, fileName)
},
error => {
console.log(error);
this.alertService.showAlert(error.message, "error");
}
);
}

这是我的angular 6版本下载代码。。在我升级到10个RequestOptions之后

请帮我另一种解决方案。。

这是(取自http.d.ts(的get方法:

get<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;

因此,您可以执行以下操作:

downloadFile(id): Observable<Blob> {
return this.http.get(this.baseUrl + `coursepurchased/receipt/` + bookingId, { responseType: "blob" });
}

组件应该看起来像:

getCourseReceipt(bookingId) {
this.studentInfoService.getCourseInvoice(bookingId).subscribe(
response => {
var fileName = 'test.pdf';
let blob:any = new Blob([response], { type: 'application/pdf; charset=utf-8' });
importedSaveAs(blob, fileName)
},
error => {
console.log(error);
this.alertService.showAlert(error.message, "error");
}
);
}

最新更新