user2999177 user2999177 - 3 months ago 23
jQuery Question

HTML5 File Reader & jQuery: How to log a file's contents to the console

I'm trying to read a text file and print its contents to the console using jquery and the HTML5 file reader. (will try to phrase it later but that's going to be another problem) to load some UI presets. But cant figure out HTML5 reader for the life of me.

Can someone tell me whats the problem with this code?

$('#fileInput').change(function() {

var file = fileInput;
var reader = new FileReader();

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

reader.readAsText(file);

console.log(fileContent);
});


https://jsfiddle.net/xLtgcg4m/

Answer
  • console.log(fileContent); should be inside the onload
  • And get the files[0]th file from file Object using file.files[0]

$('#fileInput').change(function() {

  var file = fileInput;
  var reader = new FileReader();

  reader.onload = function(e) {
    fileContent = reader.result;
    console.log(fileContent);     
  }
  reader.readAsText(file.files[0]);    

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="fileInput" title="Load File" />

files[0] 0 for the simplest reason you're not iterating over a file input with type multiple. If you used multiple than you would iterate over all files[n]