简体   繁体   English

在加载时使用 FileReader 从文件中获取文本

[英]Getting text from file using FileReader on Load

So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page.所以,我一直在处理一个只使用本地文件的页面(不幸的是,服务器不是一个选项。甚至不是本地主机。斗争是真实的。)我遇到了需要从中获取文本的情况.csv 文件并将其填充到页面。 I have this bit of code that works, but I need to have a file set within the function when a button is pressed.我有这段代码可以工作,但是当按下按钮时,我需要在函数中设置一个文件。 Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).手动查找文件不是一种选择(为了可视化我在做什么,我正在以最烦人的方式制作一个模拟数据库文件(因为我必须这样做,而不是因为我想要))。

In the page I would have something like:在页面中,我会有类似的内容:

<button id="myButton" onclick="getText()"></button>

<script>
var myFile = "dataset.csv";
...
</script>

The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.以下代码有效(关于让它从 csv 文件中提取数据),但是,正如我所说,我需要在按下按钮时从文件中提取文本,并且只需在脚本,而不是手动拉起它。

<!DOCTYPE html>
<html>
   <body>
      <input type="file" id="fileinput" />
      <div id="outputdiv"></div>
      <script type="text/javascript">
           function readSingleFile(evt) {
             var f = evt.target.files[0]; 
             if (f) {
               var r = new FileReader();
               r.onload = function(e) { 
                  var contents = e.target.result;
                      var splited = contents.split(/\r\n|\n|\r|,/g);
                      for (i=0; i<splited.length; i++){
                         document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
                      }     
                     }
               r.readAsText(f);
             } else { 
               alert("Failed to load file");
             }         
           }
           document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
      </script>
   </body>
</html>

From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader.从我从 API 中可以看出,我需要将文件属性设置为 blob,以便将其传递给 FileReader。 How I can do this without using an input box, I have no idea.我不知道如何在不使用输入框的情况下做到这一点。 There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.也有 50% 的可能性我完全错了,因为我显然不知道如何完成这项工作。

If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated.如果有人可以向我展示如何实现我正在寻找的东西,我将不胜感激。 I'm absolutely stumped.我完全被难住了。

Thank you.谢谢你。

Note: CORS restrictons will prevent this from working in most browsers.注意:CORS 限制将阻止它在大多数浏览器中工作。 You can use FireFox Developer Edition, which disables CORS validation.您可以使用禁用 CORS 验证的 FireFox Developer Edition。

You can use an XMLHttpRequest to load a local file:您可以使用 XMLHttpRequest 加载本地文件:

<!DOCTYPE html>
<html>
   <body>
      <button onclick="readSingleFile()">Click Me</button>
      <div id="outputdiv"></div>
      <script type="text/javascript">
         function readSingleFile() {
            let xhr = new XMLHttpRequest();
            let url = "relative/path/to/file.txt;
            if (!url) return;
            xhr.onload = dataLoaded;
            xhr.onerror = _ => "There was an error loading the file.";
            xhr.overrideMimeType("text/plain");
            xhr.open("GET",url);
            xhr.send();
          }

          function dataLoaded(e){
            var contents = e.target.responseText;
            var splited = contents.split(/\r\n|\n|\r|,/g);
            for (i=0; i<splited.length; i++){
              document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
            }
      </script>
   </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM