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

二次信任 提交于 2019-11-28 01:22:48

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!