Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read a text file on my local disk into a variable in javascript

Hi I am trying to read in a .json file from my local machine. it will not read it in the code I am using is:

jQuery.getJSON('../json/test.json') 
    .done(function(data) {
        var test = data;
        alert("sucsess");
    })
    .fail(function(data){
    alert("failed");

});

All I am getting from this is failed what am I doing wrong. I am not going through a server with this.

like image 945
Sagarmichael Avatar asked Jun 15 '12 08:06

Sagarmichael


3 Answers

Check this fiddle

<title>reading Text files</title> 
<body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>
    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList
        for (var i = 0, f; f = files[i]; i++) {

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function(theFile) {
            return function(e) {
                // Print the contents of the file
                var span = document.createElement('span');                    
                span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
                document.getElementById('list').insertBefore(span, null);
            };
        })(f);

        // Read in the file
        //reader.readAsDataText(f,UTF-8);
        //reader.readAsDataURL(f);

        reader.readAsText(f);
        }
    }
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
</body>
like image 174
IT ppl Avatar answered Nov 15 '22 09:11

IT ppl


Use the File APIs. Here's a guide with sample code and demos:

  • Reading files in JavaScript using the File APIs
like image 10
Jonny Buchanan Avatar answered Nov 15 '22 10:11

Jonny Buchanan


Sorry but if you run the page from local drive ( address bar will have the form file:///path to your page) then you may read a file from disk, but if your run a script from webserver (http://......) you cannot read file from local drive. It's protect you from stealing information from user drive. You may need to upload a file in order to read it

EDIT: I have to take it back. New browser will allow you to read file based on user event. If user click file input and open a file then you can read it

like image 5
James Avatar answered Nov 15 '22 11:11

James