通过a标签,实现本地动态插入文本下载文件

297 阅读1分钟

方式一:

第一步,将文本内容转为base-64

let str = '{"declaration": {}}';
// 通过window自带的方法btoa(),将内容转为base-64,注意:该方法使用 "A-Z", "a-z", "0-9", "+", "/""=" 字符来编码字符串。
// 不能直接编译中文
const result = window.btoa(str); // "ewogICAgImRlY2xhcmF0aW9uIjoge30KfQ=="
// 对应还有一个方法atob(),可以将base-64转换回来
window.atob(result ); // "{"declaration": {}}"

window.atob()

window.btoa()

第二步,通过a标签实现文件下载
let str = '{"declaration": {}}';
// 通过window自带的方法btoa(),将内容转为base-64
const result = window.btoa(str); // "ewogICAgImRlY2xhcmF0aW9uIjoge30KfQ=="
const fileType = 'text/plain';// 定义生成文件的后缀类型,还可以定义为json类型"application/json"

<a href=`data:${fileType };base64,${result}` download="file">下载文件</a>
示例
<!DOCTYPE html>
<html>
<body>

<a id="download" href='' download="file">下载文件</a>
<script>
    const download = document.querySelector('#download');
    const str = 'hello world';
    const result = window.btoa(str);
    const fileType = 'application/json';
    download.setAttribute('href',`data:${fileType};base64,${result}`)
</script>
</body>
</html>

注意:我在使用btoa方法的时候,遇见过乱码的现象,刷新浏览器之后就没有再遇见了,非常的邪乎,根据需要encodeURIComponent整一下,应该问题不大

方式二:(推荐)

通过Blob对象,创建下载链接的形式

const json = '你的数据';
let blob = new Blob([json], { type: "application/json;charset=utf-8" });
<a href={URL.createObjectURL(blob)} download="file" >下载文件</a>