- How to open a local disk file with JavaScript?
- 11 Answers 11
- Specs
- Browser compatibility
- HTML File Paths
- File Path Examples
- HTML File Paths
- Absolute File Paths
- Example
- Relative File Paths
- Example
- Example
- Example
- Best Practice
- How to specify a local file within html using the file: scheme?
- 5 Answers 5
- How to read a local text file in the browser?
- 23 Answers 23
How to open a local disk file with JavaScript?
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?
11 Answers 11
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);
Specs
Browser compatibility
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?
@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: stackoverflow.com/a/12102992/63011
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 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.
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.
A quick scan of the referenced spec (last updated 2012-07-12) shows no facilities for file writing, only reading.
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.
HTML File Paths
A file path describes the location of a file in a web site’s folder structure.
File Path Examples
Path | Description |
---|---|
The «picture.jpg» file is located in the same folder as the current page | |
The «picture.jpg» file is located in the images folder in the current folder | |
The «picture.jpg» file is located in the images folder at the root of the current web | |
The «picture.jpg» file is located in the folder one level up from the current folder |
HTML File Paths
A file path describes the location of a file in a web site’s folder structure.
File paths are used when linking to external files, like:
Absolute File Paths
An absolute file path is the full URL to a file:
Example
The tag is explained in the chapter: HTML Images.
Relative File Paths
A relative file path points to a file relative to the current page.
In the following example, the file path points to a file in the images folder located at the root of the current web:
Example
In the following example, the file path points to a file in the images folder located in the current folder:
Example
In the following example, the file path points to a file in the images folder located in the folder one level up from the current folder:
Example
Best Practice
It is best practice to use relative file paths (if possible).
When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.
How to specify a local file within html using the file: scheme?
I’m loading a html file hosted on the OS X built in Apache server, within that file I am linking to another html file in the same directory as follows:
This works. However (for reasons too lengthy to go into) I am experimenting using the file: scheme instead, however I cannot get anything to work. Here is how I am re-writing the above line using file:
Unless I missed something, file:// Points to a file on the client machine. So if you are trying to get a file that is on the server, you should keep using HTTP.
5 Answers 5
The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html . Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user’s path; ~ does no expand in a file: URL. So you would need file:///home/User/2ndFile.html (on most Unixes), file:///Users/User/2ndFile.html (on Mac OS X), or file:///C:/Users/User/2ndFile.html (on Windows).
Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file: URLs from other local pages.
To use a relative path, you just include the relative path, without any file: scheme or // . So if you have a file index.html , and want to refer to other_file.html in the same directory, you would just link directly to other_file.html with no scheme.
@Brian then there is no any way to download local file like file:///home/User/2ndFile.html ? I would like to know if there is any alternative available?
the «file://» url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the «local machine» is the machine that is running the browser.
if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.
The ‘file’ protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.
Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way.
I suspect the first file is not really loaded using an apache http server at all, but simply by opening the file? href=»2ndFile.html» simply works because it uses a «relative url». This makes the browser use the same protocol and path as where he got the first (current) file from.
The first file is loaded by a client application, the reason I’m using file:// is I’m experimenting with some security stuff and seeing if its possible for the first file to use file://.
Well that’s all fine (the little you tell). But if you use the file protocol this has nothing to do with apache. Apache is a http server.
I realize that when this answer was written it may have not been the case: The file scheme is one of the schemes mentioned in the RFC1738 and defined in RFC8089. The URL Living Standard has examples using the file scheme.
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
Did you check if you proposed solution works? If not, I recommend you do not post the answer, since it might mislead others.
For apache look up SymLink or you can solve via the OS with Symbolic Links or on linux set up a library link/etc
My answer is one method specifically to windows 10.
So my method involves mapping a network drive to U:/ (e.g. I use G:/ for Google Drive)
open cmd and type hostname (example result: LAPTOP-G666P000 , you could use your ip instead, but using a static hostname for identifying yourself makes more sense if your network stops)
Press Windows_key + E > right click ‘This PC’ > press N (It’s Map Network drive, NOT add a network location)
If you are right clicking the shortcut on the desktop you need to press N then enter
Fill out U: or G: or Z: or whatever you want Example Address: \\LAPTOP-G666P000\c$\Users\username\
related: You can also use this method for FTPs, and setup multiple drives for different relative paths on that same network.
How to read a local text file in the browser?
I’m trying to implemennt a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.
function readTextFile() < var rawFile = new XMLHttpRequest(); rawFile.open("GET", "testing.txt", true); rawFile.onreadystatechange = function() < if (rawFile.readyState === 4) < var allText = rawFile.responseText; document.getElementById("textSection").innerHTML = allText; >> rawFile.send(); >
What is going wrong here? This still doesn’t seem to work after changing the code a little bit from a previous revision and now it’s giving me an XMLHttpRequest exception 101. I’ve tested this on Firefox and it works, but in Google Chrome it just won’t work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?
@JeffreySweeney yes I’m testing this on a local machine. I have stored the text file at the same place as the javascripts and html
23 Answers 23
JS introduced the Fetch API in 2015, which replaced XMLHttpRequest with a much simpler way to get data from URLs. In this case:
fetch("myText.txt") .then((res) => res.text()) .then((text) => < // do something with "text" >) .catch((e) => console.error(e));
And since all mordern browsers severely lock down what they can do with direct filesystem access, try not to use file:/// . Even if you’re «just working locally» there are tons of light weight webservers that you can use (including things like running python -m http.server or npx http-server ) so you can load your data using normal http urls.
original answer
You need to check for status 0 (as when loading files locally with XMLHttpRequest , you don’t get a status returned because it’s not from a Webserver )
function readTextFile(file) < var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); rawFile.onreadystatechange = function () < if(rawFile.readyState === 4) < if(rawFile.status === 200 || rawFile.status == 0) < var allText = rawFile.responseText; console.log(allText); >> > rawFile.send(null); >
And specify file:// in your filename:
readTextFile("file:///C:/your/path/to/file.txt");