0

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.

1

1 Answer 1

2

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

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

5 Comments

Thanks for the comment Andrei.. the only change I had to make was using readAsText instead of readAsDataURL. Other than that, its all working now.
You are correct, I edited my answer to reflect that.
Hi Andrei, Another question, the answer works fine and displays correct value inside onload function, but when I try to print the value outside that function, the array still displays empty values. e.g. reader.onload = function (e) { uploadedClientList = e.target.result.split("\n"); console.log("Take 1:" + uploadedClientList); }; console.log("Take 2:" + uploadedClientList); Take 1 works fine, but Take 2 is still empty
Ravi, this is the way JavaScript works. JavaScript is non-blocking: there is no guarantee that uploadedClientList will be set up before Take 2 executes. One way to enforce the order of execution is to use callback functions. I think this tutorial explains it pretty well: sebastianmetzger.com/…
Thanks Andrei.. That info was really helpful.. Task completed. :)

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.