Question

The browser does not allow opening a local file using window.open('local_file.txt') and $.ajax('local_file.txt'), because of security reasons. However, I want to use the file's data in the client side. How can I read local file in JavaScript?

Solution - Use HTML5 FileReader

The HTML5 FileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

Here is an example using FileReader:

function readSingleFile(e) {
  var file = e.target.files[0];
  if (!file) {
    return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
    var contents = e.target.result;
    // Display file content
    displayContents(contents);
  };
  reader.readAsText(file);
}
 
function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.innerHTML = contents;
}
 
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
<input type="file" id="file-input" >
<div id="file-content"></div>

Solution - Use XMLHttpRequest

JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.

Here is an example to read file abc.txt:

var txt = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
  if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
    txt = xmlhttp.responseText;
  }
};
xmlhttp.open("GET","abc.txt",true);
xmlhttp.send();

References & Resources

  • https://developer.mozilla.org/en-US/docs/Web/API/FileReader
  • https://w3c.github.io/FileAPI/