javascriptcsvd3.jsfilereaderfileparsing

Parse Uploaded CSV file using D3.js


I'm new to d3.js so I know this might seem as a silly question to some so please bear with me. I'm trying to parse a csv file which a user uploads and print it's output in the console. I'm able to parse the CSV file when I provide the absolute path of the CSV file but when I try doing the same with file upload functionality I'm not getting any output in the console..

Working Javascript Code..

    var dataset = [];
    d3.csv("sample.csv", function(data) {
    dataset = data.map(function(d) { return [ d["Title"], d["Category"], d["ASIN/ISBN"], d["Item Total"] ]; });
    console.log(dataset[0]);
    console.log(dataset.length);
    }); 

Console Output...

["Men's Brooks Ghost 8 Running Shoe Black/High Risk Red/Silver Size 11.5 M US", "Shoes", "B00QH1KYV6", "$120.00 "]
 8

New HTML code..

    <input type="file" id="csvfile" name="uploadCSV"/>
    <br/>
    <button onclick="howdy()">submit</button>

Modified Javascript Code(not working)..

    var myfile = $("#csvfile").prop('files')[0];
    var reader = new FileReader();

    reader.onload = function(e) {
    var text = reader.result;
    }

    reader.readAsDataURL(myfile);

     var dataset = [];
    d3.csv(reader.result , function(data) {
    dataset = data.map(function(d) { return [ d["Title"], d["Category"], d["ASIN/ISBN"], d["Item Total"] ]; });
    console.log(dataset[0]);
    console.log(dataset.length);
    })

Since there was no official documentation on how to handle user uploaded CSV file I can't figure out where I'm going wrong..Is there a way I can use HTML5 file reader?? Please help..


Solution

  • You are close but you don't need to and can't call d3.csv on a reader.result. d3.csv makes an async AJAX call to retrieve a CSV file from a server. You already have the file contents and just want to parse, so use d3.csv.parse.

    Full working example:

    <!DOCTYPE html>
    <html>
    
    <head>
      <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
    </head>
    
    <body>
      <input type="file" onchange="loadFile()" />
    
      <script>
        var reader = new FileReader();  
        
        function loadFile() {      
          var file = document.querySelector('input[type=file]').files[0];      
          reader.addEventListener("load", parseFile, false);
          if (file) {
            reader.readAsText(file);
          }      
        }
        
        function parseFile(){
          var doesColumnExist = false;
          var data = d3.csv.parse(reader.result, function(d){
            doesColumnExist = d.hasOwnProperty("someColumn");
            return d;   
          });
          console.log(doesColumnExist);
        }
      </script>
    </body>
    
    </html>