Oto Shavadze
Oto Shavadze

Reputation: 42763

"Input type file.files" selector not working in jQuery

I'm trying to get information about the file being uploaded in an HTML input with the following code:

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = $("#my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>

But it doesn't work, and the console returns: $("#my_file").files is undefined

Upvotes: 16

Views: 32608

Answers (3)

luiges90
luiges90

Reputation: 4598

$("#my_file") is a jQuery object, and a jQuery object does not have a property files...

To get the DOM element out of jQuery, do

$("#my_file")[0].files[0].size

As an extra note, if you have not selected any file, ($("#my_file"))[0].files[0] gives you undefined and ($("#my_file"))[0].files[0].size will throw error.
You are recommended to add a check...

if ($("#my_file")[0].files.length > 0) {
    file_size = $("#my_file")[0].files[0].size
} else {
    // no file chosen!
}

Upvotes: 54

Ratilal Sundhesa
Ratilal Sundhesa

Reputation: 1

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>

Upvotes: -5

Ram
Ram

Reputation: 144689

jQuery object doesn't have files property, you can use the old getElementById or jQuery get method for selecting the DOM Element object.

$(document).ready(function() {
  $('#btn').on('click', function() {
    file_size = document.getElementById("my_file").files[0].size;
    alert(file_size);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="my_file" type="file" name="my_name" />
  <input id="btn" type="button" />
</form>

Upvotes: 6

Related Questions