以下代码实现的是点击导出按钮让用户能够下载 test.txt 文件:
<textarea id="ta_text"></textarea>
<button type="button" onclick="saveFile()">导出</button>
<script>
function exportTxt(fileName, data) {
if (navigator.userAgent.indexOf("Trident") &amp;gt;= 0) {
try {
// IE 10 或以上
var fileObj = new Blob([data]);
navigator.msSaveBlob(fileObj, fileName);
} catch (ex) {
// IE 9 或以下
var winSave = window.open();
winSave.document.open("text", "utf-8");
winSave.document.write(data);
winSave.document.execCommand("SaveAs", true, fileName);
winSave.close();
}
} else {
// Webkit
var urlObject = window.URL || window.webkitURL || window;
var export_blob = new Blob([data]);
var save_link = document.createElement("a");
save_link.href = urlObject.createObjectURL(export_blob);
save_link.download = fileName;
save_link.click();
}
}
function saveFile() {
var text = document.querySelector("#ta_text").value;
exportTxt("test.txt", text);
}
</script>
webkit 内核的浏览器会将一个链接到 blob 对象的 uri 视作下载处理,而在 IE 中似乎不能这样,所以需要单独调用 navigator.msSaveBlob 方法,而低版本的 IE 甚至不能支持 blob 对象,需要使用浏览器提供的特定 API 来实现保存功能。
考虑到兼容性等问题,实际的生产环境中不建议使用该方法,对于需要下载的功能建议由后端提供。