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!
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.
<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.
Remove the value('No file chosen'). Use . addClass() method to add the class which removes the value “No file chosen”.
The <input type="file"> defines a file-select field and a "Browse" button for file uploads.
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
doc.on('change', '#uploadFile', function(e){
var file = $(this);
var test = 'Event Triggered';
console.log(e.target.files)
});
Use event.target.files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With