0%

angular文件下载

1
// 文件下载
2
downloadPdf(id: number) {
3
  this.http.post('/api/documents', { id })
4
    .subscribe(
5
      (base64Pdf: string) => {
6
        const arrayBuffer = base64ToArrayBuffer(base64Pdf); // 创建Array缓冲区
7
        createAndDownloadBlobFile(arrayBuffer, 'testName');
8
      },
9
      error => console.error(error)
10
    )
11
}
12
13
// Base64到数组缓冲区
14
export function base64ToArrayBuffer(base64: string) {
15
  const binaryString = window.atob(base64); //如果不使用base64,则注释这个
16
  const bytes = new Uint8Array(binaryString.length);
17
  return bytes.map((byte, i) => binaryString.charCodeAt(i));
18
}
19
20
// 创建Blob对象并下载文件
21
createAndDownloadBlobFile(body, filename, extension = 'pdf') {
22
  const blob = new Blob([body]);
23
  const fileName = `${filename}.${extension}`;
24
  if (navigator.msSaveBlob) {
25
    // IE 10+
26
    navigator.msSaveBlob(blob, fileName);
27
  } else {
28
    const link = document.createElement('a');
29
    //支持HTML5下载属性的浏览器
30
    if (link.download !== undefined) {
31
      const url = URL.createObjectURL(blob);
32
      link.setAttribute('href', url);
33
      link.setAttribute('download', fileName);
34
      link.style.visibility = 'hidden';
35
      document.body.appendChild(link);
36
      link.click();
37
      document.body.removeChild(link);
38
    }
39
  }
40
}