[jquery] jQuery: read text file from file system

I am trying to read a text file using jquery, like this:

// LOAD file and split line by line and append divs
$.get('myFile.txt', function(data) {    
    var lines = data.split("\n");

    $.each(lines, function(n, elem) {
       $('#myContainer').append('<div>' + elem + '</div>');
    });
});

In chrome, I am getting:

XMLHttpRequest cannot load file:///C:/myPath/myFile.txt. Origin null is not allowed by Access-Control-Allow-Origin.

Firefox shows no error but the code is not executed (I have breakpoints in firebug and the anonymous function never runs).

Any help appreciated!

EDIT:

had to:

  • use the file full path
  • launch chrome with "--allow-file-access-from-files"

now it's working OK!

This question is related to jquery file filesystems get

The answer is


This is working fine in firefox at least.

The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.

I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:

function readFiles()
{
    $.get('file.txt', function(data) {
        alert(data);
    }, "text");
}

Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.


this one is working

        $.get('1.txt', function(data) {
            //var fileDom = $(data);

            var lines = data.split("\n");

            $.each(lines, function(n, elem) {
                $('#myContainer').append('<div>' + elem + '</div>');
            });
        });

If you include a file input box you can access the file as a base64 encoded string by using the FileReader object. If it's a text file a simple base64 decode will work to get the text.

Assuming the following HTML:

<input type="file" id="myfile" />

You can access using the following JQuery JS:

var file = $('#myfile').get(0).files[0];
var reader = new FileReader();
reader.onload = function (e) {
    //get the file result, split by comma to remove the prefix, then base64 decode the contents
    var decodedText = atob(e.target.result.split(',')[1]);
    //show the file contents
    alert(decoded);
};
reader.readAsDataURL(file);

As long as the file does not need to be dynamically generated, e.g., a simple text or html file, you can test it locally WITHOUT a web server - just use a relative path.


You can't do this without the WEB SERVER!!! Chrome sends XMLHttpRequest to the system that looks something like this

GET /myFile.txt HTTP/1.1

And the operating system is not listening on port 80 to receive this! And even if it is, it must implement HTTP protocol to communicate with the browser...

To get this working, you must have WEB SERVER installed on your system, that will listen on port 80 and make your files available through a HTTP connection, thus making your code runnable.


A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:

html:

<!DOCTYPE html>
<html>

<head>
  <script src="script.js"></script>
  <script type="text/javascript">
    function loadData() {
      // getData() will return the string of data...
      document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
    }
  </script>
</head>

<body onload='loadData()'>
  <h1>check out the data!</h1>
  <div id='data'></div>
</body>

</html>

script.js:

// function wrapper, just return the string of data (csv etc)
function getData () {
    return 'look at this line of data\n\
oh, look at this line'
}

See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\').


specify the full path of the file url


Something like this is what I use all the time. No need for any base64 decoding.

<html>
<head>
<script>
      window.onload = function(event) {
        document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
      }

      function handleFileSelect(event) {
        var fileReader = new FileReader();
        fileReader.onload = function(event) {
          $('#accessKeyField').val(event.target.result);
        }
        var file = event.target.files[0];
        fileReader.readAsText(file);
        document.getElementById('fileInput').value = null;
      }
</script>
</head>
<body>
<input type="file" id="fileInput" style="height: 20px; width: 100px;">
</body>
</html>

This doesn't work and it shouldn't because it would be a giant security hole.

Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.

While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUse knows.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?

Examples related to filesystems

Get an image extension from an uploaded file in Laravel Notepad++ cached files location No space left on device How to create a directory using Ansible best way to get folder and file list in Javascript Exploring Docker container's file system Remove directory which is not empty GIT_DISCOVERY_ACROSS_FILESYSTEM not set Trying to create a file in Android: open failed: EROFS (Read-only file system) Node.js check if path is file or directory

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?