大綱

原來的文件名稱:[JS] 20 reading CSV file.docx

相關

Demo 1 利用JS下載連結

其他

有關full path 的討論: 有關chrome app 範例

server side

HttpRequest: (from web server or absolute path)

參考

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

範例 :readTextFile("file:///C:/your/path/to/file.txt");

討論 這個方法只適用於 web server,例如下面的程式碼會發生錯誤訊息如下:

Failed to load file:///C:/temp/kk.txt: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

  



	
    
	

Just change the url to http://localhost instead of localhost. If you open the html file from local, you should create a local server to serve that html file, 簡單的解決辦法就是安裝Web Server for Chrome。 或者

跟上面一樣,只是比較容易理解:

function readFileHttp(fname, callback) {
   xmlhttp = getXmlHttp();
   xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState==4) { 
          callback(xmlhttp.responseText); 
      }
   }
   xmlhttp.open("GET", fname, true);
   xmlhttp.send(null);
}
 
/*
Return a cross-browser xmlhttp request object
*/
function getXmlHttp() {
   if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
   } else if (window.ActiveXObject) {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   if (xmlhttp == null) {
      alert("Your browser does not support XMLHTTP.");
   }
   return xmlhttp;
}

HTML

<div id="page-wrapper">

    <h1>Text File Reader</h1>
    <div>
        Select a text file: 
        <input type="file" id="fileInput">
    </div>
    <pre id="fileDisplayArea"><pre>

</div>

JS

window.onload = function() {
    var fileInput = document.getElementById('fileInput');
    var fileDisplayArea = document.getElementById('fileDisplayArea');

    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var textType = /text.*/;

        if (file.type.match(textType)) {
            var reader = new FileReader();

            reader.onload = function(e) {
                fileDisplayArea.innerText = reader.result;
            }

            reader.readAsText(file);    
        } else {
            fileDisplayArea.innerText = "File not supported!"
        }
    });
}

參考:JS on MS Windows (simple sample) Source: Working with Files

function ReadFiles()
{
   var fso, f1, ts, s;
   var ForReading = 1;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   s = ts.ReadLine();
   // s holds the text content
   ts.Close();
}