javascript读取客户端文件内容
本文使用HTML5的FileReader对象结合file对象读取客户端选中的文本类型的文件。
注意:一定要结合file对象,不可以直接指定客户端文件路径。安全问题是不允许直接访问客户端文件的,而且你指定的路径也不一定存在。之前在csdn碰到一个人以为html5是神列,什么都能做,我就呵呵了。。
备注:IE9-不支持FileReader。
javascript读取客户端文件内容源代码如下
示例文件存储编码为ANSI
编码指定为utf-8(也是默认编码),出现乱码
指定为gb2312才正确读取
<script> function readFileText(f) { if (window.FileReader) { f = f.files[0]; if (/^(text\/|application\/(xml|javascript))/g.test(f.type)) {//文本类型的 var reader = new FileReader(); reader.onload = function (r) { document.getElementById('tRst').value = r.target.result } reader.readAsText(f, document.getElementById('sEncoding').value); } else alert('请选择文本类型的文件,如.txt,.html,.aspx文件等') } } </script> <textarea id="tRst" rows="10" cols="80"></textarea><br /> <input type="file" onchange="readFileText(this)" /><br /> <select id="sEncoding"><option value="utf-8">utf-8</option><option value="gb2312">gb2312</option></select>(请选择正确的文件编码,否则包含中文会乱码。ANSI存储编码选择gb2312,否则选择utf-8)
加支付宝好友偷能量挖...
原创文章,转载请注明出处:javascript读取客户端文件内容