核心原理:将内容写入到 Blob 中,然后将其解析为一个链接,供用户下载。
涉及技术点:
- Blob 对象: 表示一个类文件对象,主要用于后续的“解析成一个链接”
- window.URL.createObjectURL: 用于生成某个 File 或 Blob 对象的链接
- a 标签用于提供“下载”功能
案例:
<body>
<button>将内容写入到文件中并下载</button>
<script>
/**
* 将 content 写入到 filename 文件中并下载到本地
* @param {string} content 待写入的内容
* @param {string} filename 下载时的文件名,注意要提供后缀名
*/
function writeFile(content, filename) {
const blob = new Blob([content], { type: 'text/plain' });
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
document.querySelector('button').onclick = () => writeFile('hello, world!', 'hello.txt')
</script>
</body>
本文介绍如何使用JavaScript中的Blob对象和window.URL.createObjectURL方法将内容写入Blob,并转化为可供下载的链接,通过一个简单的按钮实例演示了这一过程。

2259

被折叠的 条评论
为什么被折叠?



