Ravi Singh Ravi Singh - 11 days ago 6
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.

ClientIDs
1
2
3


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"/>
</div>
</form>


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

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

reader.readAsText(document.getElementById("FileUpload").files[0]);

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