HTML、JavaScript 本地文件读写

文件读取

HTML

<html>
<head>
    <script type="text/javascript" src="./js/ReadTest.js">script>
head>
<body>
<input type="file" id="file" name="files[]" multiple />
<script type="text/javascript">
    var btn=document.getElementById('file');
    btn.addEventListener('change', handleFileSelect, false);
script>
body>
html>

JavaScript(ReadTest.js)

var a = new Array();

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    if (files[0]) {
        var reader = new FileReader();
        reader.readAsText(files[0]);
        reader.onload = loaded;
    }
}

function loaded(evt) {
    var fileString = evt.target.result;
    console.log(fileString)
    alert(fileString);
}

文件写入

(使用文件下载的方式写入本地)

HTML

<html>
<head>
    <script type='text/javascript' src="./js/SaveBlob.js">script>
head>
<body>
<input type="button" id="savetext" value="Save" onclick="Save()"/>
body>
html>

JavaScript(SaveBlob.js)

function doSave(value, name) {
    var blob;
    if (typeof window.Blob == "function") {
        blob = new Blob([value]);
    } else {
        var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
        var bb = new BlobBuilder();
        bb.append(value);
        blob = bb.getBlob();
    }
    var URL = window.URL || window.webkitURL;
    var bloburl = URL.createObjectURL(blob);
    var anchor = document.createElement("a");
    if ('download' in anchor) {
        anchor.style.visibility = "hidden";
        anchor.href = bloburl;
        anchor.download = name;
        document.body.appendChild(anchor);
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, true);
        anchor.dispatchEvent(evt);
        document.body.removeChild(anchor);
    } else if (navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, name);
    } else {
        location.href = bloburl;
    }
}

var a = new Array();
for (var i = 0; i < 10; i++)
    a.push(i);

function Save() {
    // 数据,文件名
    doSave(a, "hello.json");
}

你可能感兴趣的:(html,javascript,文件读写)