Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

dom events - Reading client side text file using Javascript

I want to read a file (on the client side) and get the content in an array. It will be just one file. I have the following and it doesn't work. 'query_list' is a textarea where I want to display the content of the file.

<input type="file" id="file" name="file" enctype="multipart/form-data"/>

    <script>
       document.getElementById('file').addEventListener('change', readFile, false);

       function readFile (evt) {
           var files = evt.target.files;
           var file = files[0];

          var fh = fopen(file, 0);
          var str = "";
          document.getElementById('query_list').textContent = str;
          if(fh!=-1) {
             length = flength(fh);        
             str = fread(fh, length);     
             fclose(fh);                   
           } 
           document.getElementById('query_list').textContent = str;
        }
      </script>

How should I go about it? Eventually I want to loop over the array and run some SQL queries.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to read files on the client using HTML5's FileReader, you must use Firefox, Chrome or IE 10+. If that is true, the following example reads a text file on the client.

your example attempts to use fopen that I have never heard of (on the client)

http://jsfiddle.net/k3j48zmt/

   document.getElementById('file').addEventListener('change', readFile, false);

   function readFile (evt) {
       var files = evt.target.files;
       var file = files[0];           
       var reader = new FileReader();
       reader.onload = function(event) {
         console.log(event.target.result);            
       }
       reader.readAsText(file)
    }

For IE<10 support you need to look into using an ActiveX Object like ADO.Stream Scripting.FileSystemObject http://msdn.microsoft.com/en-us/library/2z9ffy99(v=vs.85).aspx but you'll run into a security problem. If you run IE allowing all ActiveX objects (for your website), it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...