SixtySeven
SixtySeven

Reputation: 139

Download blob in downloadLink

I want to download application/pdf in downloadLink. Is it possible? What is the simplest way to download file as pdf. I have 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();

How to download this file?

Upvotes: 0

Views: 1057

Answers (2)

TheMisir
TheMisir

Reputation: 4279

Use URL.createObjectURL instead of Blob as href attribute.

const bytes = 'abcdef';
const blob = new Blob([bytes], { type: 'application/pdf' });
const downloadLink = document.createElement('a');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'document.pdf';
downloadLink.click();

Upvotes: 0

Anyone123
Anyone123

Reputation: 53

Try this:

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);
    }

Upvotes: 1

Related Questions