How to access file element file attribute using JavaScript

I have an input element with a file type in my form. I like to check the file size before the item is loaded for verification. Using most primary web browsers (except IE, which always make things harder), I found that everyone uses an “attribute” that updates whenever I select a new file and display the file size, as well as other useful information.

Here is what I see in the Chrome web browser:

enter image description here

The question is, how can I access this value using JavaScript? I tried several ways, but no one was good for me? Any good idea please?

NOTE. I use jQuery on my website, so it doesn’t matter that there is only a regular JavaScript response.

Merianos Nikos

+5
2
//use any ol' selector to get the <input /> element:
var inputElement = document.querySelector("input[type='file']");

//then it just like you'd access any object attributes:
var fileSize = inputElement.files[0].size;
//note that it a list of files, so you can loop through them
//in case the element accepts multiple files

//if you want all of the attributes, do something like:
for (var key in inputElement.files[0])
    if (inputElement.files[0].hasOwnProperty(key))
         console.log(key,inputElement.files[0][key]);
+3

:

$("#btStartUpload").on("click", function(evt) {        

    var filesSelected = document.getElementById('btInput').files; // FileList object
    // var filesSelected = $('#btInput')[0].files; // with jQuery, any jQuery object have it DOM element accessed using [0]
    // var filesSelected = $('input[type=file]')[0].files;
    console.log(filesSelected);
});
0

All Articles