Download a blob from HTTP URL in IE 11

时光总嘲笑我的痴心妄想 提交于 2019-11-30 19:23:24

IE11 Not support URL.createObjectURL()

Work for me.

IE11 I'm use

window.navigator.msSaveOrOpenBlob(blob, fileName);

Or, If check condition.

var blob = 'Blob Data';
if(window.navigator.msSaveOrOpenBlob) {

    // IE11
    window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {

    // Google chome, Firefox, ....
    var url = (window.URL || window.webkitURL).createObjectURL(blob);
    $('#filedownload').attr('download', fileName);
    $('#filedownload').attr('href', url);  
    $('#filedownload')[0].click();
}

Read more: Fixed URL.createObjectURL() function doesn't work in IE 11

Demo: JSFiddle

Fidel90's answer works fine in IE 11 after changing the IE specific part to this:

(!window.navigator.msSaveBlob ? false : function (blobData, fileName) {
      return window.navigator.msSaveBlob(blobData, fileName);
})

In IE try window.navigator.saveBlob(fileURL,name);.

For further information take a look at the documentation at MSDN.

In the past I've created the following really handy polyfill to check on IE and otherwise use downloading via href. Maybe it will help you (or others):

//check for native saveAs function
    window.saveAs = window.saveAs || window.webkitSaveAs || window.mozSaveAs || window.msSaveAs ||
        //(msIE) save Blob API
        (!window.navigator.saveBlob ? false : function (blobData, fileName) {
            return window.navigator.saveBlob(blobData,fileName);
        }) ||
        //save blob via a href and download
        (!window.URL ? false : function (blobData, fileName) {
            //create blobURL
            var blobURL = window.URL.createObjectURL(blobData),
                deleteBlobURL = function () {
                    setTimeout(function () {
                        //delay deleting, otherwise firefox wont download anything
                        window.URL.revokeObjectURL(blobURL);
                    }, 250);
                };

            //test for download link support
            if ("download" in document.createElement("a")) {
                //create anchor
                var a = document.createElement("a");
                //set attributes
                a.setAttribute("href", blobURL);
                a.setAttribute("download", fileName);
                //create click event
                a.onclick = deleteBlobURL;

                //append, trigger click event to simulate download, remove
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
            else {
                //fallback, open resource in new tab
                window.open(blobURL, "_blank", "");
                deleteBlobURL();
            }
        });

You can then use this anywhere in your app as simple as:

window.saveAs(blobData, fileName);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!