简体   繁体   English

上传时显示预览图像

[英]Show preview image when upload

I created a image upload form where I need the image to preview when select the image. 我创建了一个图像上传表单,选择图像时需要在其中预览图像。 But when I upload the file , i must click the on the page for show it . 但是当我上传文件时,我必须单击页面上的来显示它。

    fileProgress(fileInput: any): void {
    this.fileData = <File>fileInput.target.files[0];
    this.preview();
  }

  preview(): void {
    // Show preview 
    const mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }

    const reader = new FileReader();
    reader.readAsDataURL(this.fileData);
    reader.onload = (_event) => {
      this.previewUrl = reader.result;
    }
  }

and this is html : 这是html:

 <div class="form-group kt-form__group row">
                    <!-- Preview -->
                    <div *ngIf="previewUrl!=null"
                        class="justify-content-center text-center col-lg-6 kt-margin-bottom-20-mobile">
                        <img [src]="previewUrl" />
                    </div>
                </div>

<ngx-mat-file-input (change)="fileProgress($event)"></ngx-mat-file-input>

You can use file upload 您可以使用文件上传

First, set your html like this 首先,像这样设置您的html

 <img [src]="imageSrc" style="max-width:300px;max-height:300px" />
 <input name="imageUrl" type="file" accept="image/*" (change)="handleInputChange($event)" />

Secondly, handle input file 其次,处理输入文件

imageSrc:string = '';

handleInputChange(e) {
   let file = e.dataTransfer ? e.dataTransfer.files[0] : e.target.files[0];
   let pattern = /image-*/;
   let reader = new FileReader();
   if (!file.type.match(pattern)) {
     alert('invalid format');
     return;
   }
   reader.onload = this._handleReaderLoaded.bind(this);
   reader.readAsDataURL(file);
 }

 _handleReaderLoaded(e) {
   let reader = e.target;
   this.imageSrc = reader.result;
 }

Please examine example 请检查示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM