Sergio Andrade
Sergio Andrade

Reputation: 324

Get file size in mb or kb

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">

Upvotes: 12

Views: 45159

Answers (3)

XXiVK
XXiVK

Reputation: 51

Hey i got a way to disply file size in MB or KB based on the file's size (file.size).

This is a react code snippet (not that much change for "True" JS code):

<span >
{ file.size > 1024 * 1024 ? (file.size / (1024 * 1024)).toFixed(2) + ' MB' : (file.size / 1024).toFixed(2) + ' KB' }
</span>

Explaination :

So i have a file in the UI in a variable called "file". To get the file's size it's "file.size". And here i'm displaying that in UI via a "span" tag.

If the size is more than 1mb (1024 bytes * 1024 bytes), then we dived the file size by 1mb (1024 bytes * 1024 bytes) to get size in "mb" and conserve 2 decimal spaces. If the file size is less than 1 mb then we know its "kb", so divide the file size by 1kb (1024 bytes) to get size in "kb" and conserve the 2 decimal spaces.

Likewise you can also do for "Gb" or other data formats.

Upvotes: 1

Akshaya Raghuvanshi
Akshaya Raghuvanshi

Reputation: 2277

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" />

Upvotes: 38

Pete
Pete

Reputation: 1780

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.

Upvotes: 6

Related Questions