0

Hi I am trying to read the csv file (just on front end not want to store it on back end ). The error I am getting is attached with the image below. enter image description here

The code I am trying is.

function file(){
       var fullPath = document.getElementById('upload').value;

       if (fullPath) {
            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);

       if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
       }

    alert(filename);
   // passFile(filename);
    d3.csv(filename, function(error, data) {
        if (error) throw error;
           console.log(data); // [{"Hello": "world"}, …]
    });
  }
}

I just want to read the data from file but getting this error. I have tried other ways too like This method I tried first but does not work for me. Can anyone help me out?

Smithiam
  • 162
  • 1
  • 16

1 Answers1

-1

d3.csv() function is for fetching csv file from a remote location. If you want to read a local file by <input type="file"> element, you should use FileReader to read the file by yourself and parse it with d3.csvParse() function.

For example:

function file(){
 var uploadFileEl = document.getElementById('upload');
 
 if(uploadFileEl.files.length > 0){
  var reader = new FileReader();
  reader.onload = function(e) {
   console.log(d3.csvParse(reader.result));
  }
  reader.readAsText(uploadFileEl.files[0]);
 }
}
<input type="file" id="upload" />
<button id="upload" onclick="file()">Read CSV</button>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.1/d3.min.js"></script>
Solomon Tam
  • 739
  • 3
  • 11