Validate file size in Javascript / jQuery
Fri, 03 November 2017
Sometimes you need some rather basic validation of file size. I had to write this for a project recently, where I needed to check the file size prior to upload.
After doing some digging around I came up with a cross browser solution (Safri, IE, Chrome, Firefox) that works quite well. In my example, I'm ensuring an image is no greater than 6MB in binary size.
function validate_file_size(elem, max_bytes, callback) {
var img = new Image();
var _URL = window.URL || window.webkitURL;
img.src = _URL.createObjectURL(elem);
return img.onload = function() {
if (typeof elem == 'object' && typeof elem['size'] != 'undefined') {
if (elem.size <= max_bytes) { // Max file size.
return callback(true);
}
}
return callback(false);
};
}
Now, to use this it's quite simple.
$('#fileOne input[type="file"]').on('change', function (e) {
var file = $(this)[0].files[0];
validate_file_size(
file,
6291456,
function(result){
if (!result) {
alert('The maximum file size allowed is 6 MB.');
return;
}
setTimeout(function () {
showLoad();
$('#fileOne input[type="submit"]').click();
}, 200);
}
);
});