gpt4 book ai didi

javascript - 如何在内存中创建文件供用户下载,而不是通过服务器?

转载 作者:行者123 更新时间:2023-11-28 08:08:11 26 4
gpt4 key购买 nike

有没有办法在客户端创建一个文本文件并提示用户下载它而不与服务器进行任何交互?

我知道我无法直接写入他们的计算机(安全性等),但我可以创建文件并提示他们保存吗?

最佳答案

适用于 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/24583472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com