[英]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. 在Chrome中工作,正在加载本地 html或JS文件。
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. 选择文件输入返回一个File对象。
How to create the File object without the Choose File input? 如何在没有选择文件输入的情况下创建文件对象?
From the File API : 从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.
它存储为JSON(易于阅读),但是我需要将其与源代码一起显示。
So the feature is to load the source code and JSON data, and render them together on a web page using HTML and Javascript. 因此,该功能是加载源代码和JSON数据,并使用HTML和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.
这是一项安全策略,可防止随机网站在浏览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 如果您打算做一些特殊的事情(例如要编写chrome应用程序),则可以访问一些不错的API来访问文件系统: 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: File
构造函数不会从硬盘驱动器读取文件,但评估者会创建一个虚拟文件,请考虑以下事项:
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
. 如果您正在谈论在nodejs中创建文件,那么您应该看看
fs
。
出于安全原因,所有浏览器均不支持文件字段中的预定义值,因此答案是“不”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.