【问题标题】:How do we download a pdf from external url in angular?我们如何以角度从外部网址下载pdf?
【发布时间】:2023-03-23 16:53:02
【问题描述】:

我尝试使用文件保护模块,但它在新页面中打开 URL 而不是下载。这是我使用的sn-p。谁能帮我解决这个问题?

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");

【问题讨论】:

    标签: angular typescript file download filesaver.js


    【解决方案1】:

    这对我有用:

    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}));
    }
    

    【讨论】:

    • 感谢您的回复,当我尝试该代码时,我收到此 CORS 错误“从源 'w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf' 访问 XMLHttpRequest 已被 CORS 策略阻止:对预检的响应请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。”
    猜你喜欢
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多