这对我有用:
rest.service.ts
@Injectable()
export class RestService {
constructor(private httpClient: HttpClient) {
}
public downloadPdf() {
return this.httpClient.get(`https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf`, {
responseType: 'arraybuffer',
headers: new HttpHeaders().append('Content-Type', 'application/pdf'),
});
}
}
Service 的使用(例如组件的 TS 内部):
this.restService.downloadPdf().subscribe((response: ArrayBuffer) => download(response, 'application/pdf', 'download.pdf'))
下载.function.ts
export function download(binaryData: ArrayBuffer, fileType: string, fileName: string): void {
const file: Blob = new Blob([binaryData], {type: fileType});
const url: string = window.URL.createObjectURL(file);
const anchorElement: HTMLAnchorElement = document.createElement('a');
anchorElement.download = fileName;
anchorElement.href = url;
anchorElement.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
}