jQuery download works in Chrome and not in Explorer

Viewed 96

I am using the following code to download a file to the desk top:

    $('#resourceTable tbody').on( 'click', '#getFile', function () {

        var data = resourceTable.row( $(this).parents('tr') ).data();
        var a = document.createElement('a');
        a.href = data.resourseImage

        if (data.resourseImageType === "pdf"){
            a.download = 'myfile.pdf';
        }else{
            a.download = 'myfile.jpg';
        }

        document.body.append(a);
        a.click();
        a.remove();
    });

It works in Chrome. In Explorer the download does not occure and the console message is given:

SCRIPT438: Object doesn't support property or method 'append'
resourceAdmin.js (559,10)

Line 559 is:

document.body.append(a);

I have tried:

$("document.body").append($(a));
a.click();
$(a).remove();

Works in Chrome. In Explorer (no errors) the button turns blue; however, the download popup does not appear.

3 Answers

Use element.appendChild(newElement);

or Override jquery append

$('#resourceTable tbody').on( 'click', '#getFile', function () {

        var data = resourceTable.row( $(this).parents('tr') ).data();
        var a = document.createElement('a');
        a.href = data.resourseImage

        if (data.resourseImageType === "pdf"){
            a.download = 'myfile.pdf';
        }else{
            a.download = 'myfile.jpg';
        }

        if (navigator.userAgent.search("Edge") > -1) {
            document.body.append = document.body.appendChild;              
        }

        document.body.append(a); // or use appendChild
        a.click();
        a.remove();
    });

IE doesn't support downloading that way. you should first convert the data into a blob and use an IE Specific function. Before line 559. Check whether it's a IE browser and use another method to download which is supported in IE like below-

var blob = new Blob([data.resourseImage], {type:  "text/plain;charset=utf-8;"});
if (navigator.msSaveBlob) {
    return navigator.msSaveBlob(blob, fileName);
} else {
    $("document.body").append($(a));
    a.click();
    $(a).remove();
}
Related