Javascript InvalidStateError:无法设置';价值';在'上的属性;HTMLInputElement';:具有中间模型和服务的HTTP请求
我有一个angular应用程序,它由一个表单组成,表单设置模型对象的字段,然后对象本身作为JSON发送到我的后端。但是,每当我尝试使用以下方法上载图像/文件时,我都会遇到一个错误:Javascript InvalidStateError:无法设置';价值';在'上的属性;HTMLInputElement';:具有中间模型和服务的HTTP请求,javascript,angular,angular-material,Javascript,Angular,Angular Material,我有一个angular应用程序,它由一个表单组成,表单设置模型对象的字段,然后对象本身作为JSON发送到我的后端。但是,每当我尝试使用以下方法上载图像/文件时,我都会遇到一个错误: core.js:4352 ERROR Error: Uncaught (in promise): InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a file
core.js:4352 ERROR Error: Uncaught (in promise): InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
Error: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
at EmulatedEncapsulationDomRenderer2.setProperty
我怎样才能度过这一关?此外,我无法尝试更改表单的方法,因此请尝试并建议此方法中的某些内容
html
首先,您需要删除
[(ngModel)]
,然后,将此.temp_文件
附加到表单中,然后将其上载到服务器,下面是执行http post的service.ts的示例代码:
DSD
postFile(fileToUpload:File,formData:formData):可观察{
const endpoint='您的目标url';
formData.append('my-input',fileToUpload,fileToUpload.name);
返回此.httpClient
.post(端点,formData,{headers:yourHeadersConfig})
.map(()=>{return true;})
.catch((e)=>此.handleError(e));
}
fileToUpload
是从组件发送到服务的temp_文件
。删除ngModel部分-[(ngModel)]=“temp_文件”-它应该可以工作错误不再存在,但响应中不会发送图像@摩希佐罗斯
<mat-toolbar>Avatar/Logo</mat-toolbar>
<input type="file" id="my-input" (change)="onFileSelected($event) [(ngModel)]="temp_file">
onFileSelected(event){
this.temp_file = <File>event.target.files[0];
this.detail.logo = this.temp_file;
}
export class Detail {
...
logo: File;
...
}
postFile(fileToUpload: File, formData: FormData): Observable<boolean> {
const endpoint = 'your-destination-url';
formData.append('my-input', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}