js本地文件读写

js本地文件读写

直接上代码

<!DOCTYPE html><html><head><meta charset="utf-8"><title>本地文件读写</title></head><script type="text/javascript">(function (console) {    console.save = function (data, filename) {        if (!data) {            console.error('No data');            return;        }         if (!filename) filename = 'data.json';        if (typeof data === "object") {            data = JSON.stringify(data, undefined, 4)        }         var blob = new Blob([data], {type: 'text/json'}),            e = document.createEvent('MouseEvents'),            a = document.createElement('a');        a.download = filename;        a.href = window.URL.createObjectURL(blob);        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);        a.dispatchEvent(e)    } })(console);var arr = new Array();var temp_str ="";var i = 0;function showPreview(source){var input = source;var reader = new FileReader();reader.readAsText(input.files[0]);reader.onload = function() {if(reader.result) {   //显示文件内容temp_str = reader.result;}};}function showText(){if(temp_str==""){alert("请先上传文件");}else{document.getElementById("text").innerHTML=temp_str;}}function saveText(){var text = document.getElementById("text").value;if(text==""){alert("没有内容");}else{console.save(text,"data.json");}}</script><body><div style="display: flex; justify-content: center;"><div id="div" align="center" style="width: 300px;height: 600px; background-color: #eee;"><br><input type="file" name="file" value="上传文件" onchange="showPreview(this)" /><br><br><br><br><br><input type="button" value="显示文件内容" onclick="showText()"><br><br><input type="button" value="另存文件内容" onclick="saveText()"></div><div id="div" align="center" style="width: 1000px;height: 600px; background-color: #000000;"><textarea  id="text"style="width: 1000px;height: 600px; background-color: #000000; color: #ffffff;"></textarea></div></div></body></html>
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部