I would like to be able to read a file that is stored in the same directory as the html file. When the html file is accessed by http, there is no problem; I can just use a HttpXMLRequest. However when the HTML is being read off the local disk (as with File/Open in most desktop browsers, it seems HttpXMLRequest does not work. I used to do this with a Java Applet, but (a) I've noticed that doesn't work with some browsers and (b) I'd like a solution that uses just JavaScript: no Java and no Flash.
-
of course it won't work. httpxmlrequest does an HTTP request. when you're working with `file:///` urls, there's no webserver involved, so no way to actually do an http request. – Marc B Apr 29 '13 at 16:01
-
duplicate http://stackoverflow.com/questions/585234/how-to-read-and-write-into-file-using-javascript – Daniel Moses Apr 29 '13 at 16:02
-
1@MarcB `XMLHttpRequest` handles `file:` resources just as correctly as typing them into the address bar. The only difference is the same-origin-policy rules for the `file:` scheme are different; it has nothing to do with the lack of an actual HTTP request. – apsillers Apr 29 '13 at 16:12
-
What kind of file are you trying to read and what format do you want it in in javascript, are you limited to using XMLHttp or can you use an alternative? – Xotic750 Apr 29 '13 at 16:50
-
The files are plain old ascii text. I'd like to turn file://... to a string for further processing. – Theodore Norvell Apr 29 '13 at 20:55
-
Here is a quick summary of XMLHTTPRequest behaviour on Windows XP with three Browsers. In each case I used a synchronous GET to read an ascii file that is on the same directory as the html file. Firefox 20.0.1: a syntax error is reported to the console. (I guess because the ascii file is not XML.) No other problems. IE 8. Exception "TypeError: Access is denied" (after I okayed the potential threat). Chrome 26.0: Exception "NETWORK_ERR: XMLHtttpRequest Exception 101". – Theodore Norvell Apr 30 '13 at 01:10
-
My question is not answered at "How to read and write into a file using JavaScript". Thanks. – Theodore Norvell Apr 30 '13 at 01:20
2 Answers
HttpXMLRequest as it suggests makes HTTP requests - without a webserver, this isn't possible but it's not hard to setup a localhost server.
Though I'm sure there are other opinionated people who will suggest otherwise; my preference for a windows machine is EasyPHP http://www.easyphp.org/ and XAMP if you're not using the default/preinstalled apache server.

- 370,779
- 53
- 539
- 685

- 1,145
- 9
- 17
-
Using a web server is good advice, but the whole answer is much more nuanced than you suggest here. From MDN's [XHR page](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest): "*Despite its name, `XMLHttpRequest`... supports protocols other than HTTP (including `file` and `ftp`).*" The browser abstracts the particular mechanism used to fetch the resource, which can be file access, HTTP request, or FTP request. However, the same origin policy is applied quite differently for `file` resources than it is for `http` resources. – apsillers Apr 29 '13 at 16:45
-
Does anyone know where the same site policy for XMLHpptRequest is described, especially for the file: protocol? – Theodore Norvell Apr 29 '13 at 21:16
-
One of the nice things about distributing an application in html/javascript is that it is cross platform and opens no security holes. If I have to install a web server on every users machine so that they can use my web app in an offline mode, well I'd rather not get into that, if I can avoid it. – Theodore Norvell Apr 30 '13 at 01:18
Here is a solution for reading a file into javascript, but I am unclear at present if you are limited to only AJAX style requests. Anyway, if you are not limited to only that method then you could use FileReader.
The following example uses readAsDataURL but you can use one of the other listed methods.
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);
So here is the example that will load a file, then convert it to base64 and display the resulting string for you.
CSS
#progress_bar {
margin: 10px 0;
padding: 3px;
border: 1px solid #000;
font-size: 14px;
clear: both;
opacity: 0;
-moz-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
opacity: 1.0;
}
#progress_bar .percent {
background-color: #99ccff;
height: auto;
width: 0;
}
#display {
width: 500px;
height: 150px; }
HTML
<input type="file" id="files" name="file" />
<button id="cancel">Cancel read</button>
<div id="progress_bar">
<div class="percent">0%</div>
</div>
<div>Base64 encoded result</div>
<textarea id="display"></textarea>
Javascript
/*jslint sub: true, maxerr: 50, indent: 4, browser: true */
/*global */
(function () {
"use strict";
var reader,
progress = document.querySelector(".percent"),
display = document.getElementById("display"),
iFiles = document.getElementById("files"),
bCancel = document.getElementById("cancel"),
dropZone = document.getElementById("drop_zone"),
filebox = document.getElementById("filebox"),
list = document.getElementById("list");
function abortRead() {
if (reader) {
reader.abort();
}
}
function errorHandler(evt) {
switch (evt.target.error.code) {
case evt.target.error.NOT_FOUND_ERR:
alert("File Not Found!");
break;
case evt.target.error.NOT_READABLE_ERR:
alert("File is not readable");
break;
case evt.target.error.ABORT_ERR:
break; // noop
default:
alert("An error occurred reading this file.");
};
}
function updateProgress(evt) {
// evt is an ProgressEvent.
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
// Increase the progress bar length.
if (percentLoaded < 100) {
progress.style.width = percentLoaded + "%";
progress.textContent = percentLoaded + "%";
}
}
}
function handleFileSelect(evt) {
// Reset progress indicator on new file selection.
progress.style.width = "0%";
progress.textContent = "0%";
reader = new FileReader();
reader.onerror = errorHandler;
reader.onprogress = updateProgress;
reader.onabort = function (e) {
alert('File read cancelled');
};
reader.onloadstart = function (e) {
document.getElementById('progress_bar').className = 'loading';
};
reader.onload = function (e) {
// Ensure that the progress bar displays 100% at the end.
progress.style.width = "100%";
progress.textContent = "100%";
setTimeout("document.getElementById('progress_bar').className='';", 2000);
display.value = e.target.result;
}
// Read in the image file as a binary string.
reader.readAsDataURL(evt.target.files[0]);
}
iFiles.addEventListener("change", handleFileSelect, false);
bCancel.addEventListener("click", abortRead, false);
}());
On jsfiddle
Update: from the W3C File API - working draft
This specification allows web content to read files from the underlying file system, as well as provides a means for files to be accessed by unique identifiers, and as such is subject to some security considerations. This specification also assumes that the primary user interaction is with the element of HTML forms [HTML], and that all files that are being read by FileReader objects have first been selected by the user. Important security considerations include preventing malicious file selection attacks (selection looping), preventing access to system-sensitive files, and guarding against modifications of files on disk after a selection has taken place.

- 22,914
- 8
- 57
- 79
-
My only limitation is that I'd like a solution that works on recent editions of the major desktop browsers. My old Java based method fails with Safari on Macs -- so it is out. HttpXMLRequest fails with Moz and Safari presumably because of a strict same origin policy. – Theodore Norvell Apr 29 '13 at 21:11
-
The FileReader seems to rely on input from the user. In my case the relative path to the file is in a string. – Theodore Norvell Apr 29 '13 at 21:13
-
-
Regarding security: If I'm willing to trust an EXE file that I have down-loaded to read any file on my computer, why would I be worried about an app written in HTML/JS that I have down-loaded being able to read files that are within the same directory? I think Firefox has a more sane securty model. – Theodore Norvell May 07 '13 at 12:37
-
I didn't define the behaviour, I can understand how it may be frustrating. I will update my answer with the relevant information. – Xotic750 May 07 '13 at 14:07
-
Thanks for expanding your answer. I do understand that /web/ content should not be able to read local files without express permission of the user. My question is not about web content. It is about local content. – Theodore Norvell May 10 '13 at 20:46