Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Is there any way to get size of file?

I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.

function previewImage(element) {
  var reader = new FileReader();

  reader.onload = function (event) {
    seAddArtist.imageSource = event.target.result;
    $scope.$apply();
  };
  // when the file is read it triggers the onload event above.
  reader.readAsDataURL(element.files[0]);
}


var img = new Image();
img.onload = function () {
  alert(this.width + 'x' + this.height);
}

I am implementing these two combine but how can i check the size of image?

like image 431
Usman Iqbal Avatar asked Feb 08 '18 12:02

Usman Iqbal


1 Answers

FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:

function previewImage(element) {
  var reader = new FileReader();

  reader.onload = function(event) {
    seAddArtist.imageSource = event.target.result;
    $scope.$apply();
  };

  // when the file is read it triggers the onload event above.
  reader.readAsDataURL(element.files[0]);

  //log / access file size in bytes
  console.log(element.files[0].size + ' Bytes');

  //log / access file size in Mb
  console.log(element.files[0].size/1024/1024 + ' MB');

  if (element.files[0].size/1024/1024 > 4) {
   console.log('file is bigger than 4MB);
  }
}
like image 77
lin Avatar answered Sep 28 '22 00:09

lin