【问题标题】:InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': HTTP Request with Intermediate Model and serviceInvalidStateError:无法在“HTMLInputElement”上设置“value”属性:带有中间模型和服务的 HTTP 请求
【发布时间】:2020-12-05 18:53:11
【问题描述】:

我有一个 Angular 应用程序,它由一个表单组成,该表单设置模型对象的字段,然后对象本身作为 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;
  }

details.model.ts


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

【问题讨论】:

  • 删除 ngModel 部分 - [(ngModel)]="temp_file" - 它应该可以工作
  • 错误不再存在,但图像未在响应中发送。 @Moshezauros

标签: javascript angular angular-material


【解决方案1】:

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

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

fileToUpload 是从组件发送到服务的temp_file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-26
    • 2015-02-28
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多