Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my input type=file not loading file information?

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!

like image 339
Chris Avatar asked Jul 14 '16 09:07

Chris


People also ask

How do I reset the input type file?

To reset a file input in React, set the input's value to null in your handleChange function, e.g. event. target. value = null . Setting the element's value property to null resets the file input.

How do you specify a file type in input?

<input type="file"> <input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission, or manipulated using JavaScript code and the File API.

How do I get rid of no file chosen from input type file?

Remove the value('No file chosen'). Use . addClass() method to add the class which removes the value “No file chosen”.

Which input type do we use to upload a file?

The <input type="file"> defines a file-select field and a "Browse" button for file uploads.


2 Answers

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

like image 160
Rory McCrossan Avatar answered Oct 05 '22 23:10

Rory McCrossan


doc.on('change', '#uploadFile', function(e){
    var file = $(this);
    var test = 'Event Triggered';
console.log(e.target.files)

 });

Use event.target.files

like image 37
Piyush.kapoor Avatar answered Oct 06 '22 00:10

Piyush.kapoor