使用javascript读取本地文件
默认分类 2011-12-05 02:02:07
有时候我们需要读取本地文件,下面是使用非安全脚本读取本地txt文件的方法:
- <script type="text/javascript">
- function read(file) {
- if(typeof window.ActiveXObject != 'undefined') {
- var content = "";
- try {
- var fso = new ActiveXObject("Scripting.FileSystemObject");
- var reader = fso.openTextFile(file, 1);
- while(!reader.AtEndofStream) {
- content += reader.readline();
- content += "\n";
- }
-
- reader.close();
- }
- catch (e) {
- alert("Internet Explore read local file error: \n" + e);
- }
- return content;
- }
- else if(document.implementation && document.implementation.createDocument) {
- var content = ""
- try {
- netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
- var lf = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
- lf.initWithPath(file);
- if (lf.exists() == false) {
- alert("File does not exist");
- }
-
- var fis = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
- fis.init(lf, 0x01, 00004, null);
- var sis = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
- sis.init(fis);
- var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
- converter.charset = "UTF-8";
- content = converter.ConvertToUnicode(sis.read(sis.available()));
- }
- catch (e) {
- alert("Mozilla Firefox read local file error: \n" + e);
- }
-
- return content;
- }
- }
- </script>
安全的方法是使用xmlhttp读取本地html文件:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Untitled 1</title>
- <script type="text/javascript">
- <!--
- function doit(){
-
- var xmlhttp=null;
- if(window.ActiveXObject){
- xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
- }else if (window.XMLHttpRequest){
- xmlhttp=new XMLHttpRequest();
- }
- if(xmlhttp!=null){
- xmlhttp.open("GET","book.txt",false);
- xmlhttp.send();
- alert(xmlhttp.responseText);
- }else {
- alert("Your browser does not support XMLHTTP.");
- }
-
-
- }
-
-
- </script>
- </head>
-
- <body><button type="button" onclick="doit()">doit</button>
-
- </body>
-
- </html>
>>
留言评论