我是JS初学者,尝试通过这段代码生成json格式文件并保存
<script>
var jsonArr=[];
//Generating 5 random test data for json array
for(var i = 0; i < 5; i++) {
jsonArr.push({
team: "teamA",
matchname: "Match1",
score: "32"
}); }
json_str = JSON.stringify(jsonArr); //stringify json
//Save file function
saveFile('yourfilename.json', "data:application/json", new Blob([json_str],{type:""}));
function saveFile (name, type, data) {
if (data != null && navigator.msSaveBlob)
return navigator.msSaveBlob(new Blob([data], { type: type }), name);
var a = $("<a style='display: none;'/>");
var url = window.URL.createObjectURL(new Blob([data], {type: type}));
a.attr("href", url);
a.attr("download", name);
$("body").append(a);
a[0].click();
setTimeout(function(){ // fixes firefox html removal bug
window.URL.revokeObjectURL(url);
a.remove();
}, 500);
}
</script>
这段代码可以工作,但我想将此文件保存到特定目录并覆盖以前保存的文件。如果有人可以帮忙吗? 谢谢
最佳答案
Javascript 无法访问客户端的文件系统。您只能通过下载对话框提示用户或强制下载到默认下载目录。
关于javascript - 通过覆盖前一个文件在 Javascript 中保存 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704766/