Javascript,如何读取本地文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6506518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:05:46  来源:igfitidea点击:

Javascript, how to read local file?

javascript

提问by user691285

I try to read a local file from server. I have been "googling" this topic for a while now, and some say it's impossible, others that it can be done. During this search I've found this script:

我尝试从服务器读取本地文件。我一直在“谷歌搜索”这个话题一段时间了,有人说这是不可能的,有人说可以做到。在这次搜索中,我发现了这个脚本:

Read a file using xmlhttprequest

If the HTML file with your javascript app has been saved to disk, this is an easy way to read in a data file. Writing out is more complicated and requires either an ActiveX object (IE) or XPCOM (Mozilla).

fname - relative path to the file

callback - function to call with file text

使用 xmlhttprequest 读取文件

如果您的 javascript 应用程序的 HTML 文件已保存到磁盘,这是读取数据文件的简单方法。写出更复杂,需要 ActiveX 对象 (IE) 或 XPCOM (Mozilla)。

fname - 文件的相对路径

callback - 使用文件文本调用的函数

function readFileHttp(fname, callback) {

    xmlhttp = getXmlHttp();

    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState==4) { 

            callback(xmlhttp.responseText); 

        }

    }

    xmlhttp.open("GET", fname, true);

    xmlhttp.send(null);

}

Return a cross-browser xmlhttp request object

返回一个跨浏览器的 xmlhttp 请求对象

function getXmlHttp() {

    if (window.XMLHttpRequest) {

        xmlhttp=new XMLHttpRequest();

    } else if (window.ActiveXObject) {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

    }

    if (xmlhttp == null) {

        alert("Your browser does not support XMLHTTP.");

    }

    return xmlhttp;

}

But I don't know how to use it, and how should callback function look? Could you provide an example code using these functions?

但是不知道怎么用,回调函数应该怎么看?你能提供一个使用这些函数的示例代码吗?

回答by tofarr

Being able to read a local file from your browser would be a major breach of security - I for one do not like the idea of any site I visit being able to run code in my browser that would read files from my hard drive. Typically ajax requests are limited to the domain from which the page originated. (However, you can get around this to some extent using techniques like JSONP.) Most browsers will not let you read local files even if the page originated from your local filesystem.

能够从您的浏览器读取本地文件将是对安全的重大破坏 - 我不喜欢我访问的任何站点能够在我的浏览器中运行代码以从我的硬盘驱动器读取文件的想法。通常,ajax 请求仅限于页面源自的域。(但是,您可以使用 JSONP 之类的技术在一定程度上解决这个问题。)即使页面源自您的本地文件系统,大多数浏览器也不会让您读取本地文件。

The other methods mentioned should allow you to read files from a domain (even if it is localhost), but not from your filesystem directly.

提到的其他方法应该允许您从域(即使它是本地主机)读取文件,但不能直接从您的文件系统读取。

回答by ?ukaszW.pl

With javascript you can only read files that are publicly exposed on your server. It's similar to opening it in your browser...

使用 javascript,您只能读取服务器上公开公开的文件。这类似于在浏览器中打开它...

I suggest to use jQuery library to do this, ajax request with this are much easier and supported by all major browsers:

我建议使用 jQuery 库来做到这一点,使用它的 ajax 请求要容易得多,并且所有主要浏览器都支持:

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.get/

for example you can make it like this:

例如,你可以像这样:

$.get('/content/test.html', function(data) {
  alert(data);
});

回答by Nicky Jaidev

The below code will browse a file and copy the content to a textarea:

以下代码将浏览文件并将内容复制到文本区域:

   <input type="file" id="fileinput" />
    <script type="text/javascript">
      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"))
            );  
            document.getElementById('area').value=  contents;
          }
          r.readAsText(f);

        } else { 
          alert("Failed to load file");
        }
      }

      document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
    </script>

    <textarea rows=20 id="area"></textarea>

回答by Kiran Kumar Veerabatheni

Find below the activeX script to read a local file. (works fine in IE).

找到下面的activeX脚本来读取本地文件。(在 IE 中工作正常)。

    var fso = new ActiveXObject("Scripting.FileSystemObject");
    //specify the local path to Open
    var file = fso.OpenTextFile("C:\your path\ filename", 1);
    var fileContent = file.ReadAll();
    file.Close();

    //Parse the contents
    // ex: if the content is in JSON format
    var obj = eval('(' + fileContent+ ')');

    for (var i = 0; i < obj.length; i++) {
        //Access each element
        alert(obj[i].name);
    }

回答by Ben

The function you pass in as a callback should comprise the code which actually processes the results of your initial ajax call. For example, at its simplest:

您作为回调传入的函数应包含实际处理初始 ajax 调用结果的代码。例如,最简单的:

alert("RESPONSE: " + xmlhttp.responseText;

However, we need to clarify what you're trying to do: read a file that's stored on the server? If so, that target file has to be accessible from the web (so that you can pass over its URL to your ajax call), else your code simply won't work.

但是,我们需要澄清您要做什么:读取存储在服务器上的文件?如果是这样,该目标文件必须可从 Web 访问(以便您可以将其 URL 传递给您的 ajax 调用),否则您的代码将无法工作。