How to load the contents of a local text file by n

2019-09-04 11:18发布

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.

3条回答
forever°为你锁心
2楼-- · 2019-09-04 11:29

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

查看更多
闹够了就滚
3楼-- · 2019-09-04 11:46

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

查看更多
Root(大扎)
4楼-- · 2019-09-04 11:51

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 then you should take a look at fs.

查看更多
登录 后发表回答