WEB端生成文件并下载

2,814 阅读1分钟

原理

借助Blob对象将文件内容转成二进制文件,并通过URL.createObjectURL()创建URL,借助a链接的download属性下载.

例子

创建一个json文件并下载

const content = {
    a:'test1',
    b:'test2'
}
const jsr = JSON.stringify(content);
const blob = new Blob([jsr], {type : 'application/json'});
const url = URL.createObjectURL(blob);

const a = document.createElement('a');
a.href = url;
a.download = 'test.json';
document.documentElement.appendChild(a)
a.click()
document.documentElement.removeChild(a)