首页 > 解决方案 > InvalidStateError:无法在“HTMLInputElement”上设置“value”属性:带有中间模型和服务的 HTTP 请求

问题描述

我有一个角度应用程序,它包含一个设置模型对象字段的表单,然后对象本身作为 JSON 发送到我的后端。但是,每当我尝试使用以下方法进行图像/文件上传时,都会出现错误:

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

<mat-toolbar>Avatar/Logo</mat-toolbar>
            <input type="file" id="my-input" (change)="onFileSelected($event) [(ngModel)]="temp_file">

.ts

  onFileSelected(event){
    this.temp_file = <File>event.target.files[0];
    this.detail.logo = this.temp_file;
  }

详细信息.model.ts


export class Detail {
...
    logo: File;
...
}

标签: javascriptangularangular-material

解决方案


首先,您需要删除,然后在将表单上传到服务器时[(ngModel)]附加表单,这里是执行 http 发布的 service.ts 的示例代码:this.temp_file

dsds

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)); 
}

fileToUploadtemp_file从组件发送到服务的。


推荐阅读