Search code examples
javascriptcsvfilereaderjquery-csv

JS FileReader: Read CSV from Local File & jquery-csv


I have a CSV file in the same directory as an html page, and I'd like to use FileReader to read the file contents into a jquery-csv's To Arrays function, but I can't seem to get it to work properly. I think I understand the asynchrony of this task, but have i depicted it correctly? Here, I'm trying to output the 2nd cell in the 2nd column. Thanks for any help.

<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['timeline']}]}"></script>

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript">

var reader = new FileReader();

reader.onload = function(e) {
  var text = e.target.result;
  var data = $.csv.toArrays(text);
  document.write(data[1][1]);

}

reader.readAsText('data.csv');




</script>

Solution

  • It's not going to work.You have no permissions to read files with javascript from the browser. The only way to deal with it is to create an input[type=file] tag and add onChange event to it. For example:

    document.getElementById('fileupload').addEventListener('change', function (e) {
      var files = e.target.files;
      //proceed your files here
      reader.readAsText(files[0]);
    }, false);