[javascript] How to open a local disk file with JavaScript?

I tried to open file with

window.open("file:///D:/Hello.txt");

The browser does not allow opening a local file this way, probably for security reasons. I want to use the file's data in the client side. How can I read local file in JavaScript?

This question is related to javascript

The answer is


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.

I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.


You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.

You'll have to upload the files you want.


Others here have given quite elaborate code for this. Perhaps more elaborate code was needed at that time, I don't know. Anyway, I upvoted one of them, but here is a very much simplified version that works the same:

_x000D_
_x000D_
function openFile() {
  document.getElementById('inp').click();
}
function readFile(e) {
  var file = e.target.files[0];
  if (!file) return;
  var reader = new FileReader();
  reader.onload = function(e) {
    document.getElementById('contents').innerHTML = e.target.result;
  }
  reader.readAsText(file)
}
_x000D_
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile()">Open a file</button>
<input id="inp" type='file' style="visibility:hidden;" onchange="readFile(event)" />
<pre id="contents"></pre>
_x000D_
_x000D_
_x000D_


Because I have no life and I want those 4 reputation points so I can show my love to (upvote answers by) people who are actually good at coding I've shared my adaptation of Paolo Moretti's code. Just use openFile(function to be executed with file contents as first parameter).

_x000D_
_x000D_
function dispFile(contents) {_x000D_
  document.getElementById('contents').innerHTML=contents_x000D_
}_x000D_
function clickElem(elem) {_x000D_
 // Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )_x000D_
 var eventMouse = document.createEvent("MouseEvents")_x000D_
 eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)_x000D_
 elem.dispatchEvent(eventMouse)_x000D_
}_x000D_
function openFile(func) {_x000D_
 readFile = function(e) {_x000D_
  var file = e.target.files[0];_x000D_
  if (!file) {_x000D_
   return;_x000D_
  }_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function(e) {_x000D_
   var contents = e.target.result;_x000D_
   fileInput.func(contents)_x000D_
   document.body.removeChild(fileInput)_x000D_
  }_x000D_
  reader.readAsText(file)_x000D_
 }_x000D_
 fileInput = document.createElement("input")_x000D_
 fileInput.type='file'_x000D_
 fileInput.style.display='none'_x000D_
 fileInput.onchange=readFile_x000D_
 fileInput.func=func_x000D_
 document.body.appendChild(fileInput)_x000D_
 clickElem(fileInput)_x000D_
}
_x000D_
Click the button then choose a file to see its contents displayed below._x000D_
<button onclick="openFile(dispFile)">Open a file</button>_x000D_
<pre id="contents"></pre>
_x000D_
_x000D_
_x000D_


The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.


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.

If you want to read the file abc.txt, you can write the code as:

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();

Now txt contains the contents of the file abc.txt.


Consider reformatting your file into javascript. Then you can simply load it using good old...

<script src="thefileIwantToLoad.js" defer></script>

Here's an example using FileReader:

_x000D_
_x000D_
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;
    displayContents(contents);
  };
  reader.readAsText(file);
}

function displayContents(contents) {
  var element = document.getElementById('file-content');
  element.textContent = contents;
}

document.getElementById('file-input')
  .addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>
_x000D_
_x000D_
_x000D_


Specs

http://dev.w3.org/2006/webapi/FileAPI/

Browser compatibility

  • IE 10+
  • Firefox 3.6+
  • Chrome 13+
  • Safari 6.1+

http://caniuse.com/#feat=fileapi


Try

function readFile(file) {
  return new Promise((resolve, reject) => {
    let fr = new FileReader();
    fr.onload = x=> resolve(fr.result);
    fr.readAsText(file);
})}

but user need to take action to choose file

_x000D_
_x000D_
function readFile(file) {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = x=> resolve(fr.result);_x000D_
    fr.readAsText(file);_x000D_
})}_x000D_
_x000D_
async function read(input) {_x000D_
  msg.innerText = await readFile(input.files[0]);_x000D_
}
_x000D_
<input type="file" onchange="read(this)"/>_x000D_
<h3>Content:</h3><pre id="msg"></pre>
_x000D_
_x000D_
_x000D_