How to load the contents of a local text file by name using Javascript and HTML 5?

流过昼夜 提交于 2019-12-12 05:38:22

问题


Working in Chrome, loading a local html or JS file.

I found many examples of how to load a file that is selected using the Choose File input.

However, didn't figure out how to do it given a file name without using the Choose File input.

The Choose File input returns a File object.

How to create the File object without the Choose File input?

From the File API:

new File(
  Array parts,
  String filename, 
  BlobPropertyBag properties
);

But didn't figure out what the parts and properties would be.

Edit: Use case:

I have code coverage results generated as part of a test suite. It is stored as JSON (which is easy to read), but I need to display it with the source code.

So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript.

The file would be opened from the browser and lives on the local machine. There is no server.


回答1:


The browser cannot load arbitrary files by name from your filesystem without special extensions or other shenanigans. This is a security policy to prevent random web sites from reading files from your hard disk as you browse the internet.

If you're down to do something special like if you want to write a chrome app, you could get access to some nice APIs for accessing the filesystem: https://developer.chrome.com/apps/fileSystem




回答2:


The File constructor doesn't read a file from the harddrive, but rater make a virtual file, consider this:

var file = new File(["some", "content"], "/tmp/my-name.txt");
var reader = new FileReader();
reader.onload = function() {
  console.log(reader.result); // somecontent
};

No file will be read or stored on the clients machine.

If you are talking about creating files in nodejs then you should take a look at fs.




回答3:


For security reasons all browsers don't support predefined values on file fields so the answer is you can't.



来源:https://stackoverflow.com/questions/37425002/how-to-load-the-contents-of-a-local-text-file-by-name-using-javascript-and-html

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