Skip to content Skip to sidebar Skip to footer

Js $.get Method File With Path

I want to load a *.csv file from a path which the user can choose. The path I get: C:\\Users\\... But the $.get method can't read this path. What does the path have to look like? $

Solution 1:

If you wanted to read CSV data in JavaScript from a computer you would need to instruct the user to select the file (there is no way around this, with the possible exception of a virus). However once a user selected a file you can read and parse CSV data with a small amount of JavaScript like this (demo)

With this HTML:

<input type="file"id="file" name="file" />
<table id="rows"></table>

And this JavaScript:

var output = $('#rows');
$('#file').on('change', function(evt) {
  var files = evt.target.files;
  for (var i = 0, f; f = files[i]; i++) {
    // Only process text files.if (!f.type.match('text/.*')) {
      alert('Unsupported filetype:'+f.type);
      continue;
    }
    var reader = newFileReader();
    reader.onloadend = function(evt) {
      var rows, row, cols, col, html;
      if (evt.target.readyState == FileReader.DONE) {
        output.empty();
        rows = evt.target.result.match(/[^\r\n]+/g);
        for(row = 0; row < rows.length; row++) {
          cols = rows[row].split(',');
          html = '<tr>';
          for(col = 0; col < cols.length; col++) {
            html += '<td>'+cols[col]+'</td>';
          }
          html += '</tr>';
          output.append(html);
        }
      }
    };
    // Read in the text file
    reader.readAsBinaryString(f);
  }
});

You can generate an HTML table from the contents of a CSV file (this is based on this excellent site)

Solution 2:

function getFile(fileToRead) {

            var reader = new FileReader();
            reader.readAsText(fileToRead);

            // Handle errors load
            reader.onload = loadHandler;
            reader.onerror = errorHandler;
        }

        function loadHandler(event) {
            var csv = event.target.result;
            createChart(csv);
        }

Post a Comment for "Js $.get Method File With Path"