问题描述
我尝试使用文件保护模块,但它在新页面中打开 URL 而不是下载。这是我使用的片段。有人能帮我解决这个问题吗?
this.pdfurl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
const blob = new Blob([this.pdfurl],{type:'applicaton/pdf'})
fileSaver.saveAs(this.pdfurl,"download.pdf");
解决方法
这对我有用:
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}));
}