Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get file size in mb or kb [closed]

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">
like image 855
Sergio Andrade Avatar asked Nov 04 '15 20:11

Sergio Andrade


2 Answers

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" />
like image 68
Akshaya Raghuvanshi Avatar answered Oct 04 '22 14:10

Akshaya Raghuvanshi


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.

like image 37
Pete Avatar answered Oct 04 '22 14:10

Pete