I want get the size of file in MB if the value is > 1024 or in KB if < 1024
$(document).ready(function() {
$('input[type="file"]').change(function(event) {
var _size = this.files[0].size + 'mb';
alert(_size);
});
});
<input type="file">
Please find the updated code below. See the working example here, Cheers!
(function() {
document.querySelector('input[type="file"]').addEventListener("change", function(event) {
var _size = this.files[0].size;
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'),
i=0;while(_size>900){_size/=1024;i++;}
var exactSize = (Math.round(_size*100)/100)+' '+fSExt[i];
console.log('FILE SIZE = ',exactSize);
alert(exactSize);
});
})();
<input type="file" />
Well the file size that .size returns is the bytes of 1024 would be 0.102MB. But anyways:
$(document).ready(function() {
$('input[type="file"]').change(function(event) {
var totalBytes = this.files[0].size;
if(totalBytes < 1000000){
var _size = Math.floor(totalBytes/1000) + 'KB';
alert(_size);
}else{
var _size = Math.floor(totalBytes/1000000) + 'MB';
alert(_size);
}
});
});
Keep in mind what I wrote does not check for base cases, that mean if the file is under 1000 bytes then you will get 0KB (even if it's something like 435bytes). Also if your file is GB in size then it will just alert something like 2300MB instead. Also I get rid of the decimal so if you wanted something like 2.3MB then don't use Floor.
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