1

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.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
vitbits
  • 25
  • 7

1 Answers1

3

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.

Community
  • 1
  • 1
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • So, this isn't possible without the user's input? I don't want the user to decide the file. I wish to keep it fixed each time as test.txt – vitbits Sep 25 '15 at 02:43
  • Not possible without the user's input. For security reasons. Consider what would happen if any web application you ran could silently and automatically read any file from you computer that it wanted to, but without asking you or without you when knowing it was happening. – sideshowbarker Sep 25 '15 at 02:59