简体   繁体   中英

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. 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.

<!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. 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.

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. You can use FireFox Developer Edition, which disables CORS validation.

You can use an XMLHttpRequest to load a local file:

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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