javascript - 下载按钮在 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 不支持。但我无法找到一个好的解决方法。
提前致谢!
解决方案
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>
推荐阅读
- python - 如何处理来自电报机器人的图像而不保存到文件
- hibernate-search - Hibernate-search 中的自联接(分层数据)
- node.js - 在执行“npm install”时遇到很多错误
- python-3.x - Python3 ZMQ,中断函数并在收到的每条新消息上调用另一个
- ios - 如何在Objective-C中将单斜杠“\”替换为“\\\”
- javascript - Npm 不运行 package.json 中的任何脚本
- javascript - 需要元素时更改 CSS
- angular - “对象”类型上不存在属性“地图”
- python-3.x - 我可以在云函数函数中的python中提供gcloud命令吗
- php - 在同一页面上更新 php session var?