简体   繁体   中英

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

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.

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

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 .

出于安全原因,所有浏览器均不支持文件字段中的预定义值,因此答案是“不”。

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