207

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?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
Joval
  • 2,071
  • 2
  • 13
  • 3

11 Answers11

301

Here's 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;
    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);
<input type="file" id="file-input" />
<h3>Contents of the file:</h3>
<pre id="file-content"></pre>

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

Community
  • 1
  • 1
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
  • Thanks, I tried and it worked (`fileVariable.name`). –  Oct 11 '15 at 12:31
  • 1
    Just one sec, when I reload the same last file, the content doesn't change (I say about its content, when I edit the file text). Can you help? –  Oct 11 '15 at 12:49
  • 1
    @SamusHands Yeah, you're right, I can reproduce the problem in Safari and Chrome (it works fine in Firefox). Setting the value of the input to `null` on each `onClick` event should do the trick, see: http://stackoverflow.com/a/12102992/63011 – Paolo Moretti Oct 11 '15 at 23:05
  • @paolo I'm doing a simulation, so I know the name of the local file, but I dont know how to get the file. I tried this http://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript but it is not working. – aburbanol Apr 04 '17 at 16:14
  • 7
    This is good as an example of `FileReader`, but a comment on the `displayContents` above: note that setting `innerHTML` like this with untrusted content can be a security vulnerability. (To see this for yourself, create a `bad.txt` containing something like `` and see that the alert gets executed—it could be more malicious code.) – ShreevatsaR Jun 23 '17 at 18:28
  • 4
    @ShreevatsaR really good point. My snippet is just an example, but you're right, it shouldn't promote bad security habits. I replaced `innerHTML` with `textContent`. Thanks for your comment. – Paolo Moretti Jun 24 '17 at 00:52
  • @PaoloMoretti Thanks for fixing, too bad I can't upvote again. :-) – ShreevatsaR Jun 24 '17 at 01:04
  • Is there a way to test this with a framework like jasmine? – Zanidd Mar 28 '18 at 07:42
  • If you are seeing a `Cannot read property 'addEventListener' of null`, you need to make sure the index is before the script. Just a subtle thing but it makes a difference :) – Teyler Halama May 22 '19 at 21:57
  • 1
    @TeylerHalama You can also use the [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event) event for that. – Paolo Moretti May 23 '19 at 09:33
68

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.

dda
  • 6,030
  • 2
  • 25
  • 34
HBP
  • 15,685
  • 6
  • 28
  • 34
59

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).

function dispFile(contents) {
  document.getElementById('contents').innerHTML=contents
}
function clickElem(elem) {
 // Thx user1601638 on Stack Overflow (6/6/2018 - https://stackoverflow.com/questions/13405129/javascript-create-and-save-file )
 var eventMouse = document.createEvent("MouseEvents")
 eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
 elem.dispatchEvent(eventMouse)
}
function openFile(func) {
 readFile = function(e) {
  var file = e.target.files[0];
  if (!file) {
   return;
  }
  var reader = new FileReader();
  reader.onload = function(e) {
   var contents = e.target.result;
   fileInput.func(contents)
   document.body.removeChild(fileInput)
  }
  reader.readAsText(file)
 }
 fileInput = document.createElement("input")
 fileInput.type='file'
 fileInput.style.display='none'
 fileInput.onchange=readFile
 fileInput.func=func
 document.body.appendChild(fileInput)
 clickElem(fileInput)
}
Click the button then choose a file to see its contents displayed below.
<button onclick="openFile(dispFile)">Open a file</button>
<pre id="contents"></pre>
  • 5
    Thanks, was helpful. Though note that instead of that code you have in `clickElem()`, you can instead just call `fileInput.click()`. (at least in the latest version of Chrome) – Venryx Dec 16 '18 at 23:18
  • Works for me, code on which it's based doesn't. – sketchyTech May 14 '21 at 13:59
15

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

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

async function read(input) {
  msg.innerText = await readFile(input.files[0]);
}
<input type="file" onchange="read(this)"/>
<h3>Content:</h3><pre id="msg"></pre>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • I just saw msg.innerText and for the first time I learned that some elements identified with IDs can be accessed using IDs as variable names or properties of the window object. – fmalina Feb 26 '20 at 12:58
  • so the answer is *we can't*. html seems so perfect for documents interaction ! but not everything can be served. A local file access would have been nice – yota May 22 '20 at 07:46
  • 1
    @yota - browser force user to interact (and be aware) probably because of security reasons – Kamil Kiełczewski May 22 '20 at 08:35
15

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:

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)
}
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>
Magnus
  • 1,584
  • 19
  • 14
5

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

<script src="thefileIwantToLoad.js" defer></script>
andrew pate
  • 3,833
  • 36
  • 28
  • 1
    In this case, you could format the file [as a base64 string](https://stackoverflow.com/questions/36280818/how-to-convert-file-to-base64-in-javascript) to save it in a JavaScript file. – Anderson Green Oct 30 '20 at 04:11
1

It is not related to "security reasons" . And it does not matter if it local or file on network drive. The solution for Windows OS could be IIS - Internet Information Services and this is some details :
To open file in browser with Java Script window.open() , the file should be available on WEB server.
By creating Virtual Directory on your IIS that mapped to any physical drive you should be able to open files. The virtual directory will have some http: address. So instead of window.open("file:///D:/Hello.txt");
You will write window.open("http://iis-server/MY_VIRTUAL_DRIVE_D/Hello.txt");

Oleg Kaploun
  • 287
  • 2
  • 6
0

Here is how to do it in typescript if Blob is good enough (no need to convert to ByteArray/String via FileReader for many use-cases)

function readFile({
  fileInput,
}: {
  fileInput: HTMLInputElement;
}): Promise<ArrayLike<Blob>> {
  return new Promise((resolve, reject) => {
    fileInput.addEventListener("change", () => {
      resolve(fileInput.files);
    });
  });
}

here is how to do it in vanilla javascript

function readFile({
  fileInput,
}) {
  return new Promise((resolve, reject) => {
    fileInput.addEventListener("change", () => {
      resolve(fileInput.files);
    });
  });
}

Matt Taylor
  • 11
  • 1
  • 2
-3

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.

-6

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.

dda
  • 6,030
  • 2
  • 25
  • 34
Youssef
  • 1,310
  • 1
  • 14
  • 24
-9

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.

  • 4
    @TheMuffinMan and XML.(Asynchronus Javascript and XML) – Quintec Nov 15 '14 at 18:32
  • 12
    This answer is not relevant as the op asked for how to open files that reside on the client side, not files that reside on the server. – Thomas Nguyen May 04 '15 at 19:23
  • 4
    @ThomasNguyen, this question is the first google result of "javascript open file" and this answer beneficial nonetheless. – Nathan Goings Jun 30 '15 at 03:40
  • @ThomasNguyen I agree, but a possible workaround without FileReader could be to upload the file to the server and read it from there. Still I downvoted this answer. – inf3rno Feb 13 '17 at 12:04