Get file size in mb or kb

I want to get the file size in MB if the value> 1024 or in KB if <Twenty-four

$(document).ready(function() { $('input[type="file"]').change(function(event) { var _size = this.files[0].size + 'mb'; alert(_size); }); }); <input type="file"> 
+5
source share
2 answers

Please find the updated code below. See a 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]; alert(exactSize); }); }); 
+13
source

Well, the file size that .size returns is 1024 characters, it will be 0.102 MB. But anyway:

 $(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 that I wrote that it does not check basic cases, this means that if the file is under 1000 bytes, then you will get 0 KB (even if it's something like 435 bytes). Also, if your file is GB in size, it just warns of something like 2300MB. I also get rid of the decimal, so if you want something like 2.3MB, then do not use Floor.

+1
source

Source: https://habr.com/ru/post/1235241/


All Articles