Download a blob from HTTP URL in IE 11

后端 未结 3 975
别那么骄傲
别那么骄傲 2021-01-02 01:01

My page generates a URL like this: blob:http%3A//localhost%3A8383/568233a1-8b13-48b3-84d5-cca045ae384f, blob having file data. I am downloading this as a file i

3条回答
  •  时光说笑
    2021-01-02 01:29

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

提交回复
热议问题