如何将 reader.result 转换为字符串?

How do i convert reader.result into string?

当我尝试在 angular 上上传一张图片时,下面的打字稿文件中的 reader.result 出现了一个错误,我该如何解决这个问题? 我在 onImagePicked 的函数中添加了 console.log(image) 它也没有显示在控制台中 为什么它没有显示在控制台中?

打字稿文件

     imagePreview:string;


ngOnInit(){
  this.form = new FormGroup({
    title : new FormControl(null,{validators:[Validators.required]}),
    content: new FormControl(null,{validators:[Validators.required]} ),
    image: new FormControl(null, {validators: [Validators.required]})
  });


        onImagePicked(event: Event){
          const file = (event.target as HTMLInputElement).files[0];
          this.form.patchValue({image: file});
          this.form.get('image').updateValueAndValidity();
          console.log(file);
          const reader = new FileReader();
          reader.onload = () => {
            this.imagePreview = reader.result;
          };
          reader.readAsDataURL(file);
        }

Html 文件

<mat-card>
  <mat-spinner *ngIf="isLoading"></mat-spinner>
  <form [formGroup]="form" (submit)="onAddPost()"  *ngIf="!isLoading">
    <mat-form-field>
      <input matInput type="text" formControlName="title" placeholder="title"  >
      <mat-error *ngIf="form.get('title').invalid" >Please enter the Title</mat-error>
    </mat-form-field>

    <mat-form-field>
      <textarea matInput rows="6" formControlName="content" placeholder="caption"   ></textarea>
      <mat-error *ngIf="form.get('content').invalid" >Please enter the Content</mat-error>
    </mat-form-field>
<div class='image-preview'>
  <img src="" [alt]="form.value.title">
</div>


    <div>
        <button mat-stroked-button type="button" (click)="filePicker.click()">Add Image</button>
        <input type="file" #filePicker (chnage)="onImagePicked($event)">
      </div>

    <button  mat-raised-button color="accent" type="submit">Save Post</button>
</form>
</mat-card>

根据 FileReader.result() 的官方文档,该方法的 return 值的类型可能是 stringArrayBuffer

您可能需要使用 TypeScript 的 type assertion 来告诉编译器 reader.result 是类型 string,因为您已将 imagePreview 的类型设置为 string.

reader.onload = () => {
  this.imagePreview = reader.result as string;
};

声明imagePreview的类型时同样可以设置为imagePreview: string | ArrayBuffer

或者你也可以这样做:

reader.onload = () => {
      this.imagePreview = <string>reader.result;
    }