首页 > 解决方案 > 在 downloadLink 中下载 blob

问题描述

我想在 downloadLink 中下载应用程序/pdf。可能吗?将文件下载为pdf的最简单方法是什么?我有base64string。

    const binaryString = window.atob(this.base64ToDisplay);    
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    const blob = new Blob([bytes], { type: 'application/pdf' });
    const fileName = 'example.pdf';
    const downloadLink = document.createElement('a');
    downloadLink.href = blob;
    downloadLink.download = fileName;
    downloadLink.click();

如何下载这个文件?

标签: htmlangulartypescript

解决方案


尝试这个:

private downloadFile(data: any, type: string) {
        // create blob and build an URL
        let blob = new Blob([data], { type: type });
        let url = window.URL.createObjectURL(blob);
        let downloadLink = document.createElement('a');
        downloadLink.href = url;

        // append url to element and trigger click
        downloadLink.setAttribute('download', PDF_FILE_NAME);
        document.body.appendChild(downloadLink);
        downloadLink.click();

        // clean up
        document.body.removeChild(downloadLink);
    }

推荐阅读