我需要一个函数将 javascript 变量中的字符串下载到文本文件(5-7MB)中。该功能应该跨浏览器工作。
我尝试过制作这样的下载功能,但它在 Chrome 上不起作用。 FireFox 会打开“保存”对话框,但 Chrome 不会。另外,当我在 Chrome 中禁用“询问保存文件的位置”时,它会显示“失败 - 网络错误”。由于我在本地做所有事情,所以我不明白为什么会出现这个问题。
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
这不会打开任何用于在 Chrome(版本 76.0.3809.132)上保存文件的对话框。 Microsoft Edge (44.17763.1.0) 也存在同样的问题。我希望它适用于所有浏览器,或者至少适用于 FireFox 和 Chrome。
Edit 1:Chrome 问题似乎在其他计算机上仍然存在,因此不可能是浏览器出现问题。我也更愿意制作自己的功能而不是使用其他项目(公司问题)。
Edit 2:Chrome 中锚点大小似乎限制为 2MB。有解决方法吗?有一些答案建议使用 BLOB,但我不熟悉这个概念。任何解释将不胜感激。
我发现了一个简单的修改,现在可以在我的 FireFox 和 Chrome 上运行。它使用 BLOB 来绕过锚点大小限制。但它仍然无法在 Microsoft Edge 上运行。
function download(filename, text, type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([text], { type })
);
// Use download attribute to set set desired file name
a.setAttribute("download", filename);
// Trigger the download by simulating click
a.click();
// Cleanup
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)