首页 > 解决方案 > 角度 6 文件上传预览仅在第二次上传后工作

问题描述

我使用 Angular 6。

我很简单input type="file",可以将数据传递给 img scr,显示我需要上传的图像。

当我第一次选择图像时没有任何反应,当我第二次选择图像时,我确实看到了预览图像。

我错过了什么,为什么我第一次看不到图像预览?

我的html

<div class="container" class="border">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Choose File</h3>
            <form (ngSubmit)="onSubmit()">
                <span style="color:red;" *ngIf="message">{{message}}</span>
                <input #file type="file"  ngf-max-size='10' accept='image/*' name="image" (change)="preview(file)">
                <img [src]="imgURL" height="200" width="200" *ngIf="imgURL">
                <div class="form-group">
                    <button class="btn btn-primary">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

我的打字稿

export class BottomSheetComponent implements OnInit {

  token = this.pzLogin.userLoginAccessToken;
  public imagePath;
  imgURL: any = this.pzLogin.UserLoginClaims.ImageUrl;
  public message: string;
  fileData = new FileReader();

  constructor(
    private _bottomSheetRef: MatBottomSheetRef<BottomSheetComponent>,
     private http: HttpClient, private pzLogin: PrivateZoneLoginService,
     private localStorageService: LocalStorageService) { }

 /* openLink(event: MouseEvent): void {
    this._bottomSheetRef.dismiss();
    event.preventDefault();
  }*/

  ngOnInit() {

  }

  preview(event) {

    if (event.files.length === 0) {
      return;
    }

    const mimeType = event.files[0].type;
    if (mimeType.match(/image\/*/) == null) {
      this.message = 'Only images are supported.';
      return;
    }

    const fileSize = event.files[0].size;
    if (fileSize > 200839) {
      this.message = 'Maximum upload file size 200 kb.';
      return ;
    }

    const reader  = new FileReader();
    reader.readAsDataURL(event.files[0]);

    reader.onload = () => {
    this.imgURL =  reader.result;
    this.fileData = event.files;
    };
  }

  onSubmit() {
    const formData = new FormData();
   formData.append('UploadedFile', this.fileData[0], this.fileData[0].name);
   formData.append('token', this.token);
    this.http.post('http://localhost:11111/PrivateZone/UploadUserImage', formData)
      .subscribe(res => {
        console.log('res' + res);
        this.localStorageService.setItem('UserLoginClaims', res);
      });
  }
}

标签: angulartypescriptangular6

解决方案


我在底页组件中有这个上传图片,这是一个问题。

你只需要添加 this._bottomSheetRef.containerInstance.enter();

这将加载图像

这是我所做的更改:

  this.reader.onload = () => {
      this.imgURL = this.reader.result;
       this.fileData = event.files;
       this._bottomSheetRef.containerInstance.enter();
    };

推荐阅读