Usman Iqbal
Usman Iqbal

Reputation: 2429

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?

Upvotes: 7

Views: 21087

Answers (4)

lin
lin

Reputation: 18392

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);
  }
}

Upvotes: 9

Mustkeem K
Mustkeem K

Reputation: 8768

This is working code to get file size. you will get file size in KB.

<input id="file" type="file">
<img id="filerendered" src="">

and in script tag

document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
    files = targetn.files;

// FileReader here
if (FileReader && files && files.length) {
    var thisReader = new FileReader();

    alert("your file size "+ (files[0].size)/1024 + "kb")

    thisReader.onload = function () {
        document.getElementById("filerendered").src = thisReader.result;
    }
    thisReader.readAsDataURL(files[0]);
}

// for Not supported case
else {
    // not supported
}
}

Upvotes: 0

upsidedowncreature
upsidedowncreature

Reputation: 627

You can check the file size before submitting:

<!doctype HTML>
<html>
<head>
<script>
    function checkFileSize() {
        var size = document.getElementById("fileSelector").files[0].size;
        alert("file size: " + size);
    }
</script>
</head>
<body>
    <input id="fileSelector" type="file" onchange="checkFileSize()"/>
    <input type="submit" />
</body>
</html>

Upvotes: 0

TomBombadil
TomBombadil

Reputation: 350

That might be what you want:

var size = files[0].size;

Upvotes: 1

Related Questions