验证图像尺寸-角度6

时间:2018-10-03 08:57:58

标签: javascript angular

我正在尝试验证上传的图像的宽度或高度不能超过1024px。这是我所做的,但是由于某种原因它并非每次都起作用:

readThumbUrl(event: any) {
        this.thumbnailFile = [];
        const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        const files: FileList = target.files;
        if (files) {
            this.thumbnailFile.push(files[0]);
        }

        var image;

        if (event.target.files && event.target.files[0]) {
            let reader = new FileReader();

            reader.onload = (event: ProgressEvent) => {
                this.thumbUrl = (<FileReader>event.target).result;
// This part is for validation
                image = new Image();
                image.src = (<FileReader>event.target).result;
// Here, sometimes it takes width 0 and sometimes it takes image width,
// dont know for what reason.
                if (image.width > 1024 || image.height > 1024) {
                    this.dimensionError = true;
                }
            };

            reader.readAsDataURL(event.target.files[0]);
        }

        this.videoModel.thumbnail = event.target.value;
    }

因此验证有时会触发,有时不会触发,有没有更好的方法呢?

0 个答案:

没有答案