typescript 如何使用Angular React形式将图像保存在本地存储中?

vaqhlq81  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(143)

我正在构建一个angular项目,我想使用angular reactive form上传图像,然后将该图像保存在本地存储中。
下面是“edit.component.html”的代码片段。

<form [formGroup]="form" (ngSubmit)="save()">
<label class="head1">Photo</label> <br>
<input type="file" formControlName="Photo">
<button [disabled]="form.invalid">Save</button>
</form>

下面是“edit.component.ts”的代码片段。

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray} from '@angular/forms';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent {
form=new FormGroup({
    Photo:new FormControl(null,Validators.required),
});
save(){
    var profile;

    if(localStorage.getItem("profile")==null){
      profile={};
    }
    else{
      profile=JSON.parse(localStorage.getItem("profile")!);
    }
}
}

当我在ts文件的保存()函数中添加这行const photo = this.form.get('Photo') as File;时,我得到了错误

Conversion of type 'AbstractControl<null, null> | null' to type 'File' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type 'AbstractControl<null, null>' is missing the following properties from type 'File': lastModified, name, webkitRelativePath, size, and 6 more.ts(2352)

现在,请帮助我修改或添加一些代码,以保存在localstorage中的图像,并通过在html页面中从localstorage中获取来显示该图像。

8yparm6h

8yparm6h1#

您可以使用FileReader将图像转换为字符串,因为本地存储处理字符串,然后保存它。
然后,您可以从本地存储中读取它,并使用File将其转换回文件,并将其添加到表单中。
您可以设置文件字段更改侦听器,它将获取文件,将其分配给表单并保存它。
以下是**Stackblitz**上的演示
您可以根据需要进行修改。
关键方法:
文件处理程序:

<input
    type="file"
    formControlName="Photo"
    (change)="handleFileInput($event)"
  />
handleFileInput(event: Event) {
    const target = event.target as HTMLInputElement;

    const files = target.files as FileList;

    const file = files[0];

    this.form.value.Photo = file;

    this.saveFile(file);
  }

保存文件:

saveFile(file: File) {
    const reader = new FileReader();

    reader.onloadend = () => {
      console.log(reader.result);

      this.preview = reader.result as string;

      localStorage.setItem('profile', reader.result as string);
    };
    reader.readAsDataURL(file);
  }

读取文件:

readFile() {
    const profile = localStorage.getItem('profile');

    console.log('reading ls image: ', profile);

    if (profile) {
      this.preview = profile;

      const contentType = profile.split(';')[0].replace('data:', '');

      const file = new File([profile], 'profile.jpeg', {
        type: contentType,
      });

      this.form.value.Photo = file;
    } else {
      this.preview = '';
    }
  }

相关问题