有没有办法在客户端创建一个文本文件并提示用户下载它而不与服务器进行任何交互?
我知道我无法直接写入他们的计算机(安全性等),但我可以创建文件并提示他们保存吗?
最佳答案
适用于 HTML5 浏览器的简单解决方案...
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);
}
form * {
display: block;
margin: 10px;
}
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="name" value="test.txt">
<textarea name="text"></textarea>
<input type="submit" value="Download">
</form>
使用
download('test.txt', 'Hello world!');
关于javascript - 如何在内存中创建文件供用户下载,而不是通过服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10878149/