Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - File attributes

Tags:

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"); 
like image 381
JimmyJammed Avatar asked Dec 08 '11 19:12

JimmyJammed


People also ask

How to get value of property in jQuery?

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 .

How check file is selected or not in jQuery?

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.

How do you assign a value to a file input?

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.


2 Answers

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

like image 115
adeneo Avatar answered Sep 17 '22 17:09

adeneo


<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.!

like image 30
Srinivasan.S Avatar answered Sep 21 '22 17:09

Srinivasan.S