是否有用于链接下载和数据uri的polyfill?

时间:2017-03-13 15:18:23

标签: javascript html5 polyfills

我应该由服务器生成一些代码:

table {
  max-width: 100%;
  background-color: transparent;
  text-align:center;
}
th {
  text-align: center;
}

.table {
  width: 100%;
  margin-bottom: 20px;
} 

适用于当前的chrome,firefox,opera。我希望它支持MSIE11。 Afaik <a download="test.csv" href="data:text/plain;charset=utf-8;base64,w4FydsOtenTFsXLFkXTDvGvDtnJmw7p0w7Nnw6lwLg=="> teszt </a> 就是解决方案。是否有我可以使用的现有js polyfill,或者我应该写它?

1 个答案:

答案 0 :(得分:1)

好的,我根据我在SO答案和here中找到的代码制作了一个简单的polyfill。我在MSIE11上测试它,它的工作原理。它不支持使用XHR进行文件下载,只支持数据URI。如果您想强制下载文件,我建议使用Content-Disposition响应标头。在我的情况下,服务器只是创建文件,但不应该存储它,我也需要HTML响应,所以这是要走的路。另一种解决方案是通过电子邮件发送文件,但我发现小文件更好。

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }

})();