实现思路
- 将原始数据JSON.stringfly转字符串,创建一个blob对象,将字符串传入,指定type类型为appcation/json;charset = utf-8;返回一个blob对象
- 使用 URL.createObjectURL创建一个连接url对象,将blob对象传入,把返回结果用一个变量保存,创建一个a标签,将变量赋值给a标签的href属性,触发a标签的点击事件;
- 下载完成后移除a标签,使用revokeObjectURL释放blob对象,
代码片段
const saveAsJson = (str: string) => {
const blob = new Blob([str], { type: "application/json;charset=utf-8" });
const href = URL.createObjectURL(blob);
const alink = document.createElement("a");
alink.style.display = "none";
alink.download = "allProjects.json"; // 下载后文件名
alink.href = href;
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink); // 下载完成移除元素
URL.revokeObjectURL(href); // 释放掉blob对象
};
html源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="downLoad()">点击我下载文件</button>
</body>
<script>
function downLoad(){
let obj = {
a:100
}
saveAsJson(JSON.stringify(obj))
}
function saveAsJson(str){
const blob = new Blob([str], { type: "application/json;charset=utf-8" });
const href = URL.createObjectURL(blob);
const alink = document.createElement("a");
alink.style.display = "none";
alink.download = "allProjects.json"; // 下载后文件名
alink.href = href;
document.body.appendChild(alink);
alink.click();
document.body.removeChild(alink); // 下载完成移除元素
URL.revokeObjectURL(href); // 释放掉blob对象
}
</script>
</html>
效果图