Reading client side text file using Javascript
Asked Answered
M

4

46

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.

Mullis answered 9/2, 2011 at 21:19 Comment(2)
There is a getAsText function in the spec here that does precisely what you are attempting to do.Olmsted
Waitaminute - SQL queries? Client side??Orectic
B
64

You can read files on the client using HTML5's FileReader. The following example reads a text file on the client.

Your example attempts to use fopen which is not available in Javascript.

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)
}
<input id=file type=file />
Belostok answered 9/2, 2011 at 21:41 Comment(2)
I wanted to get the text inside a text file and append it to my contenteditable div, is this applicable?Brodsky
This method also works on IE10 and newer according to this page from MS: msdn.microsoft.com/en-us/library/ie/hh673542(v=vs.85).aspxOdy
A
15

There is such thing as HTML5 FileReader API to access local files picked by user, without uploading them anywhere. It is quite new feature, but supported by most of modern browsers. I strongly recommend to check out this great article to see, how you can use it.

There is one problem with this, you can't read big files (~400 MB and larger) because straight forward FileAPI functions attempting to load entire file into memory.

If you need to read big files, or search something there, or navigate by line index check my LineNavigator, which allows you to read, navigate and search in files of any size. Try it in jsFiddle! It is super easy to use:

var navigator = new FileNavigator(file);    

navigator.readSomeLines(0, function linesReadHandler(err, index, lines, eof, progress) {    
    // Some error
    if (err) return;
    
    // Process this line bucket
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i]; 
        // Do something with it
    }
    
    // End of file
    if (eof) return;
    
    // Continue reading
    navigator.readSomeLines(index + lines.length, linesReadHandler);
});
Approximation answered 15/1, 2015 at 8:1 Comment(1)
6 yrs since last update and this lib still works like a dream. Beers on me if I ever have the chance. Great lib, did exactly what I need and easy to use. Honestly should be apart of the native HTML5 local file spec.Incalculable
O
1

Well I got beat to the answer but its different:

<input type="file" id="fi" />
<button onclick="handleFile(); return false;">click</button>

function handleFile() {
    var preview = document.getElementById('prv')
    var file = document.getElementById('fi').files[0];
    var div = document.body.appendChild(document.createElement("div"));
    div.innerHTML = file.getAsText("utf-8");
}

This will work in FF 3.5 - 3.6, and that's it. FF 4 and WebKit you need to use the FileReader as mentioned by Juan Mendes.

For IE you may find a Flash solution.

Orectic answered 9/2, 2011 at 21:48 Comment(1)
Deprecated - developer.mozilla.org/en-US/docs/Web/API/File/getAsTextBelostok
S
1

I work there, but still wanted to contribute because it works well: You can use the filepicker.io read api to do exactly this. You can pass in an dom element and get the contents back, for text or binary data, even in IE8+

Sunday answered 18/10, 2012 at 6:17 Comment(2)
This looks nice, but you should show an example, otherwise, it should be a commentBelostok
Not to mention that you have to pay for a subscription to use their API.Ody

© 2022 - 2024 — McMap. All rights reserved.