如何将本地磁盘上的文本文件读入 javascript 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11046919/
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-24 04:13:50  来源:igfitidea点击:

How do I read a text file on my local disk into a variable in javascript

javascriptjqueryjson

提问by Sagarmichael

Hi I am trying to read in a .json file from my local machine. it will not read it in the code I am using is:

嗨,我正在尝试从本地机器读取 .json 文件。它不会在我使用的代码中读取它是:

jQuery.getJSON('../json/test.json') 
    .done(function(data) {
        var test = data;
        alert("sucsess");
    })
    .fail(function(data){
    alert("failed");

});

All I am getting from this is failed what am I doing wrong. I am not going through a server with this.

我从中得到的一切都失败了我做错了什么。我不会通过这个服务器。

采纳答案by Jonny Buchanan

Use the File APIs. Here's a guide with sample code and demos:

使用文件 API。这是包含示例代码和演示的指南:

回答by IT ppl

Check this fiddle

检查这个小提琴

<title>reading Text files</title> 
<body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>
    <script>
      function handleFileSelect(evt) {
        var files = evt.target.files; // FileList object

        // Loop through the FileList
        for (var i = 0, f; f = files[i]; i++) {

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function(theFile) {
            return function(e) {
                // Print the contents of the file
                var span = document.createElement('span');                    
                span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
                document.getElementById('list').insertBefore(span, null);
            };
        })(f);

        // Read in the file
        //reader.readAsDataText(f,UTF-8);
        //reader.readAsDataURL(f);

        reader.readAsText(f);
        }
    }
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
    </script>
</body>

回答by Trinh Hoang Nhu

Sorry but if you run the page from local drive ( address bar will have the form file:///path to your page) then you may read a file from disk, but if your run a script from webserver (http://......) you cannot read file from local drive. It's protect you from stealing information from user drive. You may need to upload a file in order to read it

抱歉,但是如果您从本地驱动器运行页面(地址栏将具有格式 file:///path 到您的页面),那么您可以从磁盘读取文件,但是如果您从网络服务器(http://. .....) 您无法从本地驱动器读取文件。它可以保护您免于从用户驱动器窃取信息。您可能需要上传文件才能阅读

EDIT: I have to take it back. New browser will allow you to read file based on user event. If user click file input and open a file then you can read it

编辑:我必须把它拿回来。新浏览器将允许您根据用户事件读取文件。如果用户单击文件输入并打开文件,则您可以读取它

回答by mas-designs

You can't acess files on your local machine via JavaScript due to security reasons etc....

由于安全原因等,您无法通过 JavaScript 访问本地计算机上的文件...

JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files.

JavaScript 和 DOM 为恶意作者提供了通过 Web 提供在客户端计算机上运行的脚本的可能性。浏览器作者使用两个限制来控制这种风险。首先,脚本在沙箱中运行,在沙箱中它们只能执行与 Web 相关的操作,而不能执行诸如创建文件之类的通用编程任务。

But I've found this website but never gave that a try, maybe helps you: Reading local files in JavaScript

但我找到了这个网站,但从未尝试过,也许对你有帮助: 用 JavaScript 读取本地文件

Edit:If you are never gonna run your code on a webserver and only execute it on your local system(calling index.html in browser like: C:/Users/user/index.html you could access it, but if this website should ever gonna go online, which I suppose, that's not going to work

编辑:如果你永远不会在网络服务器上运行你的代码而只在你的本地系统上执行它(在浏览器中调用 index.html 像:C:/Users/user/index.html 你可以访问它,但如果这个网站应该永远上网,我想,那是行不通的

回答by deej

If you're talking about file on local (client) system and not server, than that's not possible with simple javascript. You can't access local file system resources.

如果您谈论的是本地(客户端)系统而不是服务器上的文件,那么使用简单的 javascript 是不可能的。您无法访问本地文件系统资源。

回答by Vilius Gaidelis

jQuery.getJSON call is asynchronous, so you can see your test variable only inside function(data){...}

jQuery.getJSON 调用是异步的,因此您只能在 function(data){...} 中看到您的测试变量