How can I use filereader to parse csv file and convert it into an array?

1.7k views Asked by At

I have this in my html page:

<input type="file" id="fileInput" />

and this in my javascript page:

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

fileInput.addEventListener('change', function (e) {
    // code that handles reading the text file
    var file = fileInput.files[0];
    var textType = /text.*/;
    // checks if the file is a text file
       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!";
        }
    });
}

I want to be able to convert the Filereader into an array so I can do something like:

document.getElementById("today").innerHTML = today[0];

Is this possible? I also don't think this is the way to read a csv file using filereader.

UPDATE: I have figured out how to get the csv file and turn it into an array by the following code:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "text",
        success: function (data) { processData(data); }
    });
    function processData(csv) {
        var temp = new Array();
        temp = csv.split(",");
        document.getElementById("today").innerHTML = temp[0];
    }
});

Now I am wondering if there is a way to use FileReader() so I can select the file from the html page instead of using url: "data.csv" so I can select multiple files.

1

There are 1 answers

0
MaKR On

You can handle this a few ways. You might think to ajax the file to a PHP script, then do something like $csvData[] = fgetcsv($file). Then you can echo json_encode($csvData);. It may be an extra http/server request but processing files is much easier.

There are some Javascript libraries that you wouldn't need to run server-side scripts for - JQuery CSV and PapaParse