Search code examples
javascripthtmlfilereaderfileapi

Normal file reading using File API


I'm stuck with handling File APIs in my HTML program. This is my code so far:

<html>
<script>
var file = 'C://test.txt';
var myBlob = new Blob([file], {type : "text/plain"});
var myReader = new FileReader();
myReader.addEventListener("loadend", function(e){
    document.write(e.srcElement.result);
});
myReader.readAsText(myBlob);
</script>
</html>

The problem is, when I run it, the output is C://test.txt. But I want to output the contents of my file and not my file name. I've checked that my Browser's up to date. It is also necessary that I stick to HTML and JavaScript. Please help.


Solution

  • In general the code for your app can’t obtain the contents of a file from the user’s filesystem without an explicit action from the user to initiate the filesystem access—but there are exceptions and you can read more about them at https://stackoverflow.com/a/22033170/2827823.

    So for your Web app running from some arbitrary origin to get access to files from a user’s local filesystem, you must provide something to enable users themselves to select the files they want your app to use; essentially that means doing either of the following in your code:

    • include an <input type="file"> element in the markup of your document
    • create a drag-and-drop dropzone in your document, for users to drag files into

    MDN has a really good Using files from web applications how-to that goes into all the details of how to make it work.

    There’s also a very good HTML5Rocks Reading files in JavaScript using the File APIs guide that provides similar information and examples.