用Javascript从本地目录读取文件 [英] Read file from local directory in Javascript
问题描述
我需要使用Javascript(或使用JQuery,没关系)从计算机硬盘驱动器中的特定路径读取文件.我一直在谷歌搜索,但我发现的东西并没有真正的帮助.我拥有的最接近的东西是:
I need to read a file from a specific path in the hard drive of my computer using Javascript (or using JQuery, it doesn't matter). I have been searching in Google but the things that I found are not really helpful. The closest thing that I have is:
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.\n"
+"name: " + f.name + "\n"
+"type: " + f.type + "\n"
+"size: " + f.size + " bytes \n"
+ "starts with: " + contents.substr(1, contents.indexOf("\n"))
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
它允许使用文件选择器选择文件,然后显示文件的内容.我需要执行一个程序来读取您明确给出位置的文件,例如 c:\files\test.txt,并打印 test.txt 文件的内容.
It allows to select a file using a file chooser, and then it display the contents of the file. I need to do a program that reads a file in which you give the location explicitly, for example c:\files\test.txt, and it prints the contents of the test.txt file.
我在谷歌上搜索了很多没有成功,欢迎任何帮助.
I Googled this a lot without success, any help is welcome.
推荐答案
如果我错了,有人会纠正我,但据我所知,由于安全问题,这在 JavaScript 中是不可能的.
Someone correct me if I'm wrong but as far as I know this is not possible in JavaScript due to security concerns.
如果是这样,网页可以在未经您同意或您不知情的情况下抓取您文件系统上的任何文件.这是一个主要的安全问题,所以我认为这是不可能的.
If it were, a web page could grab any file on your file system without your consent or without you knowing. This is a major security concern so I dont believe it is possible.
必须允许用户在知情的情况下从其文件系统中选择文件.
A user must be given the option to choose a file from their file system knowingly.
这篇关于用Javascript从本地目录读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!