简体   繁体   English

将字节数组转换为blob(pdf文件)并使用angular 5下载

[英]Convert byte array into blob (pdf file) and download using angular 5

I'm receiving a byte array from server side and has converted it successfully to blob. 我从服务器端收到一个字节数组,并将其成功转换为blob。 However, when I'm trying to download it, it shows the file is corrupted. 但是,当我尝试下载它时,它显示文件已损坏。 Below are my codes - 以下是我的代码 -

// In client side controller
this.contractsService.downloadPdf(id)
      .then((result) => {
        var blob = new Blob([result], { type: "application/pdf" });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "testing.pdf";
        link.click();
      });

And, 和,

// In client side service
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
downloadPdf(id: number) {
    return this.http.get(this.apiRoutes.download + "/" + id, { headers: this.headers })
      .map((res: any) => res)
      .toPromise();
  }

Any sort of help will be very much appreciated. 任何形式的帮助将非常感谢。 Thank you. 谢谢。

Install file-saver 安装文件保护程序

npm i --save file-saver@latest

Your service method 您的服务方式

downloadPdf(id: number) {
    return this.http
              .get(this.apiRoutes.download + "/" + id, { responseType:'blob' })
      .toPromise();
  }

Now in your component 现在在您的组件中

import { saveAs } from 'file-saver'

this.contractsService.downloadPdf(id)
      .then(blob=> {
         saveAs(blob, 'testing.pdf');
      });

This should do the trick. 这应该可以解决问题。 The HttpClient will now extract the file from the stream. HttpClient现在将从流中提取文件。 Also have a look in the documentation for blobs with the HttpClient . 还可以看一下使用HttpClient的 blob文档。

In client side service, try explicitly setting the response type of the get request: 在客户端服务中,尝试显式设置get请求的响应类型:

downloadPdf(id: number) {
    return this.http.get(this.apiRoutes.download + "/" + id, { headers: this.headers; responseType: 'arraybuffer' })
      .map((res: any) => res)
      .toPromise();
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM