简体   繁体   中英

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.

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.

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.

I am experiencing the same problem these days. I need the website to display some data each time I launch the webpage. The data need to be adaptive to each launch, automatically, so I don't think @Augusto 's link could solve your question.

After trying out different ways (including writing a temporary local XLM or JSON file), I finally persuade myself that maybe "replacing" the "data" in the html file could be the most straightforward way.

I have a html template, within which there is a string like [data]. Each time when launch the webpage, [data] will be replaced by real data like [1,2,3]. So actually it is the new file that is launched.

You can go to enter link description here to see how the "replace" is done. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM