0

I have simple input file which accepts only images. I want to show the success message on upload any images which is less than 2mb size. But when i choose the image and inspect element, the image is converting to base64 format and size of the base64 sting is exceeding (4/3 ratio) the actual size of the image.

My question is
1. how to keep the size same as the actual image.?
2. Is there any other way to fix it.

My code is:

<input type="file" onchange="uploadImage(event)" />

jQuery

function uploadImage(event){
var fileReader = new FileReader();

if (fileReader && fileList && fileList.length) {
            $scope.fileSize = fileList[0].size;
            fileReader.readAsDataURL(fileList[0]);

            var ext = fileList1.value.match(/\.([^\.]+)$/)[1].toLowerCase();
            switch (ext) {
                case 'jpg':
                case 'bmp':
                case 'png':
                case 'tif':
                case 'jpeg':
                    $scope.hasInvalidFiles = false;
                    fileReader.onload = function (event) {

                        var imageData = event.target.result;
                        console.log(imageData);
                    }

                    if (fileList[0].size < 2000) {
                             console.log("success");
                    }
                    else {
                        console.log("Failure");
                    }
                    break;
                default:
                   console.log("Invalid");
            }
        }

}
JustCode
  • 661
  • 1
  • 8
  • 19
  • 1
    Converting to base64 always inflates file size, since there are less bits used from the bytes – Ferrybig Oct 17 '19 at 06:25
  • Possible duplicate of [base64 encoded image size](https://stackoverflow.com/questions/11402329/base64-encoded-image-size) – Liam Oct 17 '19 at 07:27

1 Answers1

0

function uploadImage(event) {
  var file = event.target.files[0]
  var fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onload = function(e) {
    console.log(e.target.result)
    var imgBase = e.target.result;
    if (imgBase.split(',')[0].indexOf('base64') >= 0) {
      var result = imgBase.split(',')[1]; // This is the actual size.
    }
  }
  if (file.size < 2 * 1024 * 1024) {
    alert("Success");
  } else {
    alert("Failure");
  }
}
<input type="file" accept="image/png, image/jpeg" onchange="uploadImage(event)" />

If you want to accepts only images. You can use accpet attribute. In addition, the unit of the size value in the File object is byte not kb.

sugars
  • 1,473
  • 7
  • 17