使用 Angular 5 验证上传的图像大小



我目前正在开发一个角度网络应用程序,其中功能是照片上传。

我想对图像大小进行验证,以便在图像太小时可以抛出错误。

这是我的代码:

public onImageDrop(evt: any) {
evt.stopPropagation();
evt.preventDefault();
this.croppieImage = null;
this.onCropeMode = true;
const image: HTMLImageElement = new Image();
const file: File = evt.dataTransfer.files[0];
const myReader: FileReader = new FileReader();
myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;
});
myReader.readAsDataURL(file);
**console.log(image.height);
console.log(image.width);**
this.photoInDragMode = false;
this.uplodedPhotoFileName = file.name;
this.uplodedPhotoFileMimeType = file.type;
this.showPhotoSaveButton = true;
this.onCropeMode = true;
}

我遇到的问题是

console.log(image.height);
console.log(image.width);

总是给我看

> 0
> 0

如果有人能帮忙,我真的很感激。

提前感谢伙计们。

HTML

<input type='file'
formControlName="img_name"
class="form-control"
(change)="readUrl($event)">

TS

readUrl(event: any) {
if (event.target.files && event.target.files[0]) {
if (event.target.files[0].type === 'image/jpeg' || 
event.target.files[0].type === 'image/png' || 
event.target.files[0].type ==='image/jpg') {
if (event.target.files[0].size < 200 * 200) {/* Checking height * width*/ }
if (event.target.files[0].size < 2000000) {/* checking size here - 2MB */ }
}
}

得到 0 是因为放置控制台日志时尚未加载映像。它已加载

myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;
});

所以你可以做一些类似的事情

myReader.onloadend = ((loadEvent: any) => {
image.src = loadEvent.target.result;
this.croppieImage = myReader.result;

});
image.onload = function(){
// image  has been loaded
console.log(image.height);
};

试试这个

reader.onload = (event) => { 
var img = new Image;
this.url = event.target.result;
img.src = event.target.result;
console.log(img.width);
}

例如:https://stackblitz.com/edit/angular-file-upload-preview-yxuayc

最新更新