Skip to content Skip to sidebar Skip to footer

Automatically Load Csv/txt File From Local Drive Into Html Page As Table Javascript

I found a lot of good suggestions on how to load a csv/txt file into a html page into a table, but none of the solutions are working for me. Here is the code I am working with. I

Solution 1:

You can't access local files with JS. That would be serious security vulnerability, because you could send a malicious webpage to a user, which would download their files and send them to someone. As midrizi mentioned in the comments, you'll need a server to download files from there.

Solution 2:

As others have noted, you can't automatically read a local file into the browser.

But you can prompt the user to select a file, using the <input type="file"> element.

Once a file has been selected via that input, it can be read via JavaScript.

<labelfor="file">Select a Text File:</label><br /><inputid="file"type="file" /><br/><buttononclick="readFile()">Read File</button><br/>
let input = document.getElementById('file');
  let contents = document.getElementById('contents');

  functionreadFile () {
    let file = input.files[0];
    const reader = newFileReader();
    reader.onload = function (evt) {
      console.log('reader.onload');
      contents.innerHTML = String(evt.target.result);
    };
    reader.readAsText(file);
  }

Solution 3:

If you can modify the data.txt a bit you can just load it as another script file without need for a server.

Change data.txt to this

var data = `heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2`

And load it as a javascript file before your actual script

<scripttype="text/javascript"src="data.txt"></script>

Then you can use the variable data which holds your file content without any ajax call.

Solution 4:

There is no way you can retrieve a local file if you don't serve it, as pointed out in the comments to your question.

There are approaches you can take to that, though. If you can't serve it by any means, you could create a GitHub repo and upload your file there. Then you can use the link to your raw file:

enter image description here

And you can also take steps to automate that, but it should be easy enough committing your file locally whenever you update it and push it to GitHub. Just in case you're not familiar with Git and GitHub, here's a handy ref.

A word of caution: unless you have total control over the characters that you include in your CSV, parsing them by naively splitting commas like that might result in ugly stuff if the values within contain commas themselves. Some CSV files also come with extra stuff in the beginning of the file (like the sep indicator in the first row, which defines what character to interpret as separator). You may completely ignore these warnings if you're producing the CSV yourself.

Also I noticed your function does not take care of building the actual table, so I changed it so it does. I also used Fetch API to retrieve the data:

<!DOCTYPE html><!-- saved from url=(0014)about:internet --><htmllang="en"><html><head><title>Test</title></head><body><scripttype="text/javascript">functionprocessData(csv) {

      let data = csv.split(/\r\n|\n/).map(v => v.split(','));

      let headers = data.shift();

      let table = document.createElement('table');

      let thead = document.createElement('thead');
      table.appendChild(thead);

      thead.innerHTML = '<tr><th>' + headers.join('</th><th>') + '</th></tr>';

      let tbody = document.createElement('tbody');
      table.appendChild(tbody);

      for (let row of data) {
        tbody.innerHTML += '<tr><td>' + row.join('</td><td>') + '</td></tr>';
      }

      document.body.appendChild(table);

    }

    // I uploaded the CSV to a personal repo for this example,// but you CAN use a local file as long as you *serve* itfetch("https://raw.githubusercontent.com/gyohza/test/master/so/data.txt")
      .then(res => res.text())
      .then(text =>processData(text));
  </script></body></html>

Post a Comment for "Automatically Load Csv/txt File From Local Drive Into Html Page As Table Javascript"