【问题标题】:Unable to download pdfs in my angular application无法在我的 Angular 应用程序中下载 pdf
【发布时间】:2021-09-19 12:15:11
【问题描述】:

我有一个烧瓶 get api,只要点击 api,它就会下载一个 zip 文件。

api - https://example.com/downloads/user1

在我的 Angular 应用程序中,我放置了一个调用服务的下载按钮。

下载.service.ts

@Injectable()
export class downloadService extends BaseService {

protected modelUrl: string = 'downloads';

constructor(protected http: Http, protected _router: Router, protected _authService: AuthService) {
super(http, _router, _authService);
}

fetchDownloadUrl(body:any): Observable<Result> {
  return this.get(this.getUrl() + "/downloads/" + body);
} 
}

在我的 download.component.ts 中

function () {
    
    self.downloadService.fetchDownloadUrl(user).subscribe(
      response => {
        swal({
          position: "center",
          title: "Downloaded!",
          type: "success",
          timer: 1500,
          showConfirmButton: false
        });
      }

当我点击按钮时,它应该会点击服务中的 api。但我得到的是 pdf 作为响应,而不是在我的本地机器上下载。

当我直接在我的 chrome 中点击 url 时,我可以下载。

我在这里错过了什么?

【问题讨论】:

    标签: angular api frontend


    【解决方案1】:

    首先在fetchDownloadUrl中,添加httpOptions responseType。

    下载.service.ts

    fetchDownloadUrl(body:any): Observable<Result> {
       const httpOptions = {
          'responseType'  : 'blob' as 'json'
        };
    
      return this.get(this.getUrl() + "/downloads/" + body, httpOptions);
    }
    

    下载.component.ts

    function () {
        
        self.downloadService.fetchDownloadUrl(user).subscribe(
          response => {
          downloadPdfFile(response)
            swal({
              position: "center",
              title: "Downloaded!",
              type: "success",
              timer: 1500,
              showConfirmButton: false
            });
          }
          
          
    downloadPdfFile(data : any) {
        console.log(data)
        let file = new Blob([data], {type: 'application/pdf'});
        var fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      }
    

    在您的 html 文件中的某处

    <button (click)="download();">Download</button>
    

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2011-08-23
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 2013-02-09
      • 2012-05-22
      相关资源
      最近更新 更多