6

Trying to get my head around this. I have an <input type='file'> element which is being used to upload files as an alternative to a drag and drop option for users with older browsers.

The drag and drop upload works fine, but for some reason when selecting files using the input, the files object returns undefined.

In the example below I've included a test variable to check that the event listener is working - which it is - but the attempts to log the contents of the file are not working - whether I try to log the full object or an individual property.

Here is the code:

HTML:

 <input type="file" id='uploadFile'>

Javascript (jQuery)

 doc.on('change', '#uploadFile', function(){
    var file = $(this);
    var test = 'Event Triggered';
    console.log(test);               //Returns 'Event Triggered'
    console.log(file.files);         //Returns undefined
    console.log(file.files[0]);      //Returns TypeError: cannot read property '0' of undefined
 });

Where am I going wrong? Can't help but feel that this is a stupid oversight somewhere but any help would be appreciated.

Thanks!

Chris
  • 1,863
  • 5
  • 30
  • 43
  • Possible duplicate of [Reading file contents on the client-side in javascript in various browsers](http://stackoverflow.com/questions/750032/reading-file-contents-on-the-client-side-in-javascript-in-various-browsers) – Liam Jul 14 '16 at 09:58

4 Answers4

6

The files property is on the DOMElement, not a jQuery object. Try this:

$(document).on('change', '#uploadFile', function() {
    var file = $(this)[0]; // note the [0] to return the DOMElement from the jQuery object
    var test = 'Event Triggered';

    console.log(test);
    console.log(file.files);
    console.log(file.files[0]);
});

Working example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
3
doc.on('change', '#uploadFile', function(e){
    var file = $(this);
    var test = 'Event Triggered';
console.log(e.target.files)

 });

Use event.target.files

Piyush.kapoor
  • 6,715
  • 1
  • 21
  • 21
  • All good answers, but I liked this one the best as it looks the cleanest. - thanks everyone! – Chris Jul 14 '16 at 13:06
3

It is my solution:

$('#uploadFile').change(function()
{
   console.log(this.files);         
   console.log(this.files[0]);
});
The KNVB
  • 3,588
  • 3
  • 29
  • 54
2

try this console.log($('#uploadFile')[0].files[0]);

enter link description here Hope this helps

Community
  • 1
  • 1
Deshan
  • 56
  • 2