Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  187] [ 5]  / answers: 1 / hits: 17279  / 6 Years ago, thu, february 8, 2018, 12:00:00

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?


More From » angularjs

 Answers
43

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

[#55220] Tuesday, February 6, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;