我正在构建一个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中获取来显示该图像。
1条答案
按热度按时间8yparm6h1#
您可以使用
FileReader
将图像转换为字符串,因为本地存储处理字符串,然后保存它。然后,您可以从本地存储中读取它,并使用
File
将其转换回文件,并将其添加到表单中。您可以设置文件字段更改侦听器,它将获取文件,将其分配给表单并保存它。
以下是**Stackblitz**上的演示
您可以根据需要进行修改。
关键方法:
文件处理程序:
保存文件:
读取文件: