Ravi Singh Ravi Singh - 9 months ago 54
PHP Question

JavaScript: Convert uploaded CSV file contents to Array

I need some help with converting uploaded csv file contents to an array using JavaScript code.

Following is what I have done so far:

I've a csv file, that contains list of all clientIDs e.g.


Using following html code, I upload the file

<form id = "FileUpload" method="post" enctype="multipart/form-data">
<div> <p><p>
<b>Select file containing all clientIDs:</b>
<input type="file" id="FileUpload" name="csv"/>
<input type="hidden" name="action" value="upload"/>
<input type="submit" name="FileUpload" value="Upload File"/>

Now, the part I am stuck at. The JS that read and converts file contents

if(document.getElementById("FileUpload").value != "") {
console.log("The file was uploaded");
//Process the file and convert its contents to array

Can someone please help?

Thanks in advance.

Answer Source

Assuming the id's are separated by new line, you can do something like this:

var reader = new FileReader();

reader.onload = function (e) {
    var arr = e.target.result.split("\n");
    // Continue processing...


See also: https://developer.mozilla.org/en/docs/Web/API/FileReader