【问题标题】:how to download a pdf file from an url in angular 5如何从 Angular 5 中的 url 下载 pdf 文件
【发布时间】:2018-10-06 22:03:04
【问题描述】:

我目前在这个问题上花了一天时间,仍然无法从 Angular 5 中的 url 下载文件

leadGenSubmit() {

    return this.http.get('http://kmmc.in/wp-content/uploads/2014/01/lesson2.pdf',
    {responseType:ResponseContentType.Blob}).subscribe((data)=>{
        console.log(data);
        var blob = new Blob([data], {type: 'application/pdf'});
        console.log(blob);
        saveAs(blob, "testData.pdf");
    },
    err=>{
        console.log(err);
        }
    )
}

当我运行上面的代码时,它显示以下错误

ERROR TypeError: req.responseType.toLowerCase is not a function
    at Observable.eval [as _subscribe] (http.js:2187)
    at Observable._trySubscribe (Observable.js:172)

我该如何解决这个问题。任何人都可以发布正确的代码以从 angular 5 的 url 下载 pdf 文件吗?

【问题讨论】:

  • responseType 是一个标题吗?不应该是Accept吗?

标签: angular5


【解决方案1】:

我认为你应该像这样定义 header 和 responseType:

let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' });

【讨论】:

  • 显示“请求的资源上不存在“Access-Control-Allow-Origin”标头”问题
  • @federer 然后这是服务器问题,因为服务器不允许 cors
  • 那么请求的网络服务器不允许 CORS。如果它是您的后端服务,您必须在您的服务器上允许跨源
  • 什么有效?你要求下载它,而不是显示它
  • 启用cors后可以使用,但是如何将我的文件名设置为要下载的文件名?
【解决方案2】:

试试这个

let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.http.get(url, { headers: headers, responseType: 'blob' as 'json' });

参考资料:

【讨论】:

    【解决方案3】:

    这是我基于 Angular 中的 ID 打开 PDF 的简单解决方案:

    在我的服务中,我创建了这个方法:

    public findById(id?: string): Observable<Blob> {
      return this.httpClient.get(`${this.basePath}/document` + '/' + id, {responseType: 'blob'});
    }
    

    然后在我的组件中,我可以使用这个方法(在按钮或其他的后面):

    showDocument(documentId: string): void {
      this.yourSuperService.findById(documentId)
        .subscribe((blob: Blob): void => {
          const file = new Blob([blob], {type: 'application/pdf'});
          const fileURL = URL.createObjectURL(file);
          window.open(fileURL, '_blank', 'width=1000, height=800');
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2020-06-02
      • 2019-01-24
      • 2020-11-04
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多