Get file size in mb or kb
Please find the updated code below. See the working example here, Cheers!
$(document).ready(function() {
$('input[type="file"]').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);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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.