js 读本地文件

http://www.jb51.net/article/21191.htm

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js 读本地文件</title> <script src="jquery.js"></script> </head> <body> <input type="file" id="data" name=""> <a href="#" onclick="load()">Load</a> <br/> <div id="editor" contentEditable="true" style="height: 250px;"></div> <script> function load() { var finput = document.getElementById("data"); // var editor = document.getElementById("editor"); var f = finput.files[0]; if(f){ var r = new FileReader(); r.onload = function(e){ var result = e.target.result; if(result){ var errMsg = ''; var codeList = []; var lines = result.split('\r\n'); for(var i=0; i<lines.length; i++){ var line = lines[i].split(','); if(line[0] != '' && line[1] != ''){ codeList.push({"code": line[0],"weight": line[1]}) }else{ errMsg += ('数据格式不正确: ' + line); } } if(codeList.length > 0){ show(codeList); } if(errMsg != ''){ alert(errMsg); } } } r.readAsText(f); } // else{ // editor.InnerHTML = "Failed to load file"; // } } function show(codeList){ for(var i=0; i<codeList.length;i++){ console.log('line ' + i + ' code: ' + codeList[i].code + ' weight: ' + codeList[i].weight); } } </script> </body> </html>

 

posted @ 2018-05-03 17:10  jamess  阅读(196)  评论(0编辑  收藏  举报