Trying to access file attributes from an input field after a file is selected. Tried this but get the error 'file not defined'
var file = $("#uploadedfile").prop("files")[0]; var fileName = file.fileName; var fileSize = file.fileSize; alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
As of jQuery 1.6, the . prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. For example, selectedIndex , tagName , nodeName , nodeType , ownerDocument , defaultChecked , and defaultSelected should be retrieved and set with the .
length property in jQuery to check the file is selected or not. If element. files. length property returns 0 then the file is not selected otherwise file is selected.
The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
If #uploadedfile
is an input with type "file" :
var file = $("#uploadedfile")[0].files[0]; var fileName = file.name; var fileSize = file.size; alert("Uploading: "+fileName+" @ "+fileSize+"bytes");
Normally this would fire on the change event, like so:
$("#uploadedfile").on("change", function(){ var file = this.files[0], fileName = file.name, fileSize = file.size; alert("Uploading: "+fileName+" @ "+fileSize+"bytes"); CustomFileHandlingFunction(file); });
FIDDLE
<form id = "uploadForm" name = "uploadForm" enctype="multipart/form-data"> <label for="uploadFile">Upload Your File</label> <input type="file" name="uploadFile" id="uploadFile"> </form> <script> $('#uploadFile').change(function(){ var fileName = this.files[0].name; var fileSize = this.files[0].size; var fileType = this.files[0].type; alert('FileName : ' + fileName + '\nFileSize : ' + fileSize + ' bytes'); }); </script>
Note: To get the uploading file name means then use jquery val() method.
For Ex:
var fileName = $('#uploadFile').val();
I checked this above code before post, it works perfectly.!
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