这是我创建的一个解决方案,它允许您单击创建和下载文件:
<html>
<body>
<button onclick='download_file("my_file.txt", dynamic_text())'>Download</button>
<script>
function dynamic_text() {
return "create your dynamic text here";
}
function download_file(name, contents, mime_type) {
mime_type = mime_type || "text/plain";
var blob = new Blob([contents], {type: mime_type});
var dlink = document.createElement('a');
dlink.download = name;
dlink.href = window.URL.createObjectURL(blob);
dlink.onclick = function(e) {
// revokeObjectURL needs a delay to work properly
var that = this;
setTimeout(function() {
window.URL.revokeObjectURL(that.href);
}, 1500);
};
dlink.click();
dlink.remove();
}
</script>
</body>
</html>
我通过改编此 HTML5 演示中的代码并弄乱事情直到它起作用来创建它,所以我确定它存在问题(如果您有改进,请发表评论或编辑!)但它是一个有效的单击解决方案.
(至少,它适用于 Windows 7 中最新版本的 Chrome)