1

I am trying to read and load a locally stored text file (it's saved on the user's computer, but may be moved to a local directory) into a variable or array so that I can generate a table with it in HTML.

I have found a way to have the user select and upload the file, but the code displays the text on the browser. I want it stored so I can manipulate the data so that I can put it in the correct row and cell. I know how to create a table, format it, format and splice text and things similar to that.

The code, which I found here but forgot which specific ask it was, goes as follows

<div id="page-wrapper">

<h1>Text File Reader</h1>
<div>
    Select a text file: 
    <input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>

</div>

<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');

fileInput.addEventListener('change', function(e) {
    var file = fileInput.files[0];
    var textType = /text.*/;

    if (file.type.match(textType)) {
        var reader = new FileReader();

        reader.onload = function(e) {
            fileDisplayArea.innerText = reader.result;
        }

        reader.readAsText(file);    
    } else {
        fileDisplayArea.innerText = "File not supported!"
    }
});
}

</script>

For reference, here's a sample of the text file and here's what I want.

enter image description here

I am still relatively new to HTML and Javascript, but eager to learn. Anything will be appreciated.

1 Answer 1

1

You already have some parts working:

  1. You have found a way to have the user select and upload the file

  2. You know how to create a table, format it, format and splice text and things

Now we need to connect these things. Unfortunately, now all the script does is display the text on the browser when the user loads a text file. This is the part of the code responsible for that:

reader.onload = function(e) {
            fileDisplayArea.innerText = reader.result;
        }

It displays it inside the <pre id="fileDisplayArea"><pre> area of your html. You want to store it inside a variable, so you can start to create a table, format it, format and splice text and things (the part 2 you already know):

reader.onload = function(e) {
            myTextToFormat = reader.result;
            // start formatting and make it into a table...

        }
Sign up to request clarification or add additional context in comments.

1 Comment

I feel silly for not having seen this. Helped a lot. Thank you for your clear explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.