【问题标题】:Validation on Uploaded Image Size using Angular 5使用 Angular 5 验证上传的图像大小
【发布时间】:2018-08-27 14:48:32
【问题描述】:

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

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

这是我的代码:

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

如果有人能提供帮助,我真的很感激。

提前谢谢各位。

【问题讨论】:

    标签: javascript angular image typescript validation


    【解决方案1】:

    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 */ }
      }
    }
    

    【讨论】:

    • 图像分辨率与文件大小没有直接关系。 size 属性只表示文件中的字节数。
    【解决方案2】:

    您得到 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);
    };
    

    【讨论】:

    • 嗨@fransyozef,感谢您的快速回复,实际上我之前尝试过那个东西,但我得到了 TypeError: Cannot read property 'height' of null
    • 我已经用图像变量上的 onload 事件编辑了我的解决方案
    【解决方案3】:

    试试这个

     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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多