Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a local file using JavaScript HTML5 file api (offline website)

I am working on an web site which will be packed in an .exe file. So the site will only be used offline. Now i need to parse an local xml document. How can i get the file handle to a local file using html5 file api?

EDIT: I dont want to use <input...> or dragging file into browser.

like image 555
user1324258 Avatar asked Dec 07 '22 06:12

user1324258


2 Answers

I'm afraid I may be the bearer of bad news for your design: The action you are requesting expressly violates the security model as specified in the File API spec. The client implementation of FileReader() must make sure that "all files that are being read by FileReader objects have first been selected by the user." (W3C File API , 13. Security Considerations: http://www.w3.org/TR/FileAPI/#security-discussion).

It would be a huge security risk of browser scripts could just arbitrarily open and read any file from a path without any user interaction. No browser manufacturer would allow unfettered access to the entire file system like that.

If your script really needs that XML file, you are going to have to instruct users on how to grant the browser access to it, as every browser will prevent your code from opening it directly without user action.

like image 199
Phil Nicholas Avatar answered Dec 08 '22 20:12

Phil Nicholas


Well, technically there is indeed a way, but you're going to (hopefully) need to bypass the browser's security settings, and it is inherently unsafe, but no more so than anything else requiring specific file locations.

That said...

<html>
  <head>
    <script>
      function foo(){
        //insert desired filereading script here.
      }
      document.getElementById("fileFoo").click();
    </script>
  </head>
  <body>
     <input type="file" id="fileFoo" display="hidden" value="filepath.extension" onclick="foo"/>
  </body>
</html>

Naturally, I've kept this vague (and slightly unorthodox) for my reasons, but provided you have the necessary control over the environment, it's completely possible.

like image 45
Algorath Avatar answered Dec 08 '22 20:12

Algorath