【问题标题】:Download pdf from REST API with correct encoding使用正确的编码从 REST API 下载 pdf
【发布时间】:2021-08-20 07:49:14
【问题描述】:

我正在尝试使用这两种方法从 rest api 下载 pdf 文件:

download(): ng.IPromise<Blob> {
    return this.$http.get<ArrayBuffer>(this.urls.getUrl())
        .then(response => {
                return new Blob([response.data], {type: 'application/pdf'});
              }
        )
}
this.service.download().then( file => {
        var a = document.createElement("a"),
            url = URL.createObjectURL(file);
        open(url)
        a.href = url;
        a.download = 'invoice';
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
              document.body.removeChild(a);
              window.URL.revokeObjectURL(url);
        }, 0);
}

而且创建的 Blob 的编码似乎存在一些问题。如果我从 Postman 调用此端点并选择“保存响应”然后选择“保存到文件”,我会得到正确的 pdf。当我使用提供的代码时,文件似乎编码不正确(用vim打开的结构通常相似,但符号不同)。

【问题讨论】:

    标签: javascript angular rest pdf encoding


    【解决方案1】:

    在服务中,您可以像这样使用 httpOptions:

       download() {
        const httpOptions = {
          responseType: 'blob' as 'json',
        };
        return this.http.get<any>(
          ServerUrl + `/api/getfile`,
          httpOptions
        );
      }
    

    您也可以在您的组件上调用服务并像这样下载 pdf:

    this.api.download().subscribe(
      (idata) => {
        let blob = new Blob([idata], { type: 'application/pdf' 
         });
        var downloadURL = window.URL.createObjectURL(idata);
        var link = document.createElement('a');
        link.href = downloadURL;
        link.download = 'invoice.pdf';
        link.click();
      },
      async (err) => {
        
      }
    );
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 1970-01-01
      • 2018-08-09
      • 2020-12-18
      • 2018-12-21
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      相关资源
      最近更新 更多