使用JS的 FileReader 读取本地文本文件(可兼容各种浏览器)


最近需要在客户端操作文件,看到网上有  FileReader 对象,链接: https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
还是直接上代码吧,大家自己看:
 
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
        function upload(input) {  
            //支持chrome IE10  
            if (window.FileReader) {  
                var file = input.files[0];  
                filename = file.name.split(".")[0];  
                var reader = new FileReader();  
                reader.onload = function() {  
                    console.log(this.result);  
                }  
                reader.readAsText(file);  
            }   
            //支持IE 7 8 9 10  
            else if (typeof window.ActiveXObject != 'undefined'){  
                var xmlDoc;   
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");   
                xmlDoc.async = false;   
                xmlDoc.load(input.value);   
                console.log(xmlDoc.xml);   
            }   
            //支持FF  
            else if (document.implementation && document.implementation.createDocument) {   
                var xmlDoc;   
                xmlDoc = document.implementation.createDocument("", "", null);   
                xmlDoc.async = false;   
                xmlDoc.load(input.value);   
                console.log(xmlDoc.xml);  
            } else {   
                alert('error');   
            }   
        }  
    </script>
</head>
<body>
<input type="file" onchange="upload(this)" />  
</body>
</html>
复制代码

不仅可以读取文本文件,还可以读取JS文件,CSS,HTML等纯文本格式,下面是运行效果(读取了oracle的tnsnames.ora文件)

 

 

出处:https://www.cnblogs.com/yaotome/p/9002172.html


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM