Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download PDF not working with Firefox using Angular 2 and Node.js

I am getting base64 string from node JavaScript back-end. But it is not working like Chrome.

I can't find any solutions in web. Getting 200 status in API call but it is not downloading file in Firefox while same code working fine with Chrome.

Here is my code::

static downloadFile(fileName: string, fileMimeType: string, uri: string) {
    const dataURI = uri;
    const blob = this.dataURIToBlob(dataURI);
    const url = URL.createObjectURL(blob);
    const blobAnchor = document.createElement('a');
    const dataURIAnchor = document.createElement('a');
    blobAnchor.download = dataURIAnchor.download = fileName;
    blobAnchor.href = url;
    dataURIAnchor.href = dataURI;

    blobAnchor.onclick = function () {
        requestAnimationFrame(function () {
            URL.revokeObjectURL(url);
        });
    };

    blobAnchor.click();
}

static dataURIToBlob(dataURI) {

    const binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len),
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    for (let i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
    }

    return new Blob([arr], {
        type: mimeString
    });

}

I am getting all the data from Node.js and working fine with Chrome. So I can't find any issue why it is not working with Firefox.

like image 229
Yash Avatar asked Nov 01 '18 09:11

Yash


1 Answers

In firefox you have to append your a into DOM and then perform click.

Used document.body.appendChild(blobAnchor); to append into DOM.

Added blobAnchor.className = 'hidden'; so it will not be visible.

And removed from DOM after few seconds with setTimeout(() => blobAnchor.remove(), 300);.

static downloadFile(fileName: string, fileMimeType: string, uri: string) {
    const dataURI = uri;
    const blob = this.dataURIToBlob(dataURI);
    const url = URL.createObjectURL(blob);
    const blobAnchor = document.createElement('a');
    const dataURIAnchor = document.createElement('a');
    blobAnchor.download = dataURIAnchor.download = fileName;
    blobAnchor.className = 'hidden';
    blobAnchor.href = url;
    dataURIAnchor.href = dataURI;
    document.body.appendChild(blobAnchor);

    blobAnchor.onclick = function () {
        requestAnimationFrame(function () {
            URL.revokeObjectURL(url);
            setTimeout(() => blobAnchor.remove(), 300);
        });
    };

    blobAnchor.click();
}

static dataURIToBlob(dataURI) {

    const binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len),
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    for (let i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
    }

    return new Blob([arr], {
        type: mimeString
    });    
}
like image 163
Karan Avatar answered Sep 25 '22 09:09

Karan