<!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; ">
<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; ">
<textarea id="text"style="width: 1000px;height: 600px; color: #ffffff;"></textarea>
</div>
</div>
</body>
</html>