首页 > 解决方案 > 下载按钮在 Internet Explorer 上不起作用

问题描述

我正在研究thymeleaf,在我的代码中我有一个触发javascript函数的下载按钮。该按钮在 chrome 上运行良好,但在 Internet Explorer 上运行良好。

Javascript代码:

function Download(containerid) {
        var fileName =  'tags.txt';
            var elHtml = document.getElementById(containerid).innerHTML;
            var link = document.createElement('a');
            mimeType = 'text/html' || 'text/plain';
            link.setAttribute('download', 'ApiResponse.txt');
            link.setAttribute('href', 'data:' + mimeType + ';charset=utf-8,' + encodeURIComponent(elHtml));
            link.click(); 
        }

调用它的 HTML:

<div class="tooltipp">
    <img onclick="Download('responseMessageEndpoint')"
    style="width: 20px; height: 20px;" th:src="@{css/download.jpg}" />
    <span class="tooltiptextt">Download</span>
</div>

从我用谷歌搜索的内容来看download.createElement('a'),IE 不支持。但我无法找到一个好的解决方法。

提前致谢!

标签: javascripthtmlspringinternet-explorer

解决方案


IE 浏览器不支持下载属性。您可以尝试使用 msSaveOrOpenBlob 方法在 IE 浏览器中下载文件。

尝试使用以下代码:

<script>
    function Download(containerid) {
        var returnedData = document.getElementById(containerid).innerHTML;
        var filename = "hello.txt";
        var BOM = "\uFEFF"; 

        if (navigator.msSaveBlob) {                // ie block
            console.log("found msSaveBlob function - is't IE")
            var blobObject = new Blob([BOM + returnedData], { type: ' type: "text/plain;charset=utf-8"' });
            window.navigator.msSaveOrOpenBlob(blobObject, "hello.txt");
        }
        else {                                     // non-ie block
            console.log("not found msSaveBlob function - is't not IE")
            var a = window.document.createElement('a');
            a.setAttribute('href', 'data:text/plain; charset=utf-8,' + encodeURIComponent(BOM + returnedData));
            a.setAttribute('download', 'hello.txt');
            a.click();
        }
    }
</script>

推荐阅读