首页 > 解决方案 > Angular 4:文件上传:无法在“HTMLInputElement”上设置“value”属性

问题描述

**TS FILE**
export class CreateqpComponent implements OnInit {
  createQPForm:FormGroup;
  constructor(private fb:FormBuilder,private http:Http) { }

  ngOnInit() {
    this.createQPForm=this.fb.group({
      qpName:['',[Validators.required]],
      file:['',[Validators.required]]
    });  

  }

  onFileChange(event) {
    if (event.target.files.length > 0 ){
      const file1=event.target.files[0];
      this.createQPForm.get('file').setValue(file1);
    }
    
  }
<form [formGroup]="createQPForm" (ngSubmit)="createQP()">
    <div class="form-group">
        <label for="qpName" class="col-sm-3 col-form-label">File Name</label>     
        <input type="text" class="form-control" formControlName="qpName" id="qpName" placeholder="SeaQueenBoat">
    </div>
    <div class="form-group">
         <label for="file" class="col-sm-3 col-form-label">Select File:</label>
         <input type="file" accept=".zip" class="form-control" formControlName="file" (change)="onFileChange($event)"/>
     </div>
</form>

当我选择一个文件时,它给了我一个错误:

ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

我是 Angular 的新手,无法找到其他解决方案。

谁能解释我如何解决这个错误?

标签: angulartypescript

解决方案


您可以将文件保存在 ts 文件中的变量中,并在提交表单时使用它:-

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html'
})
export class FileUpload implements OnInit {

  createQPForm: FormGroup;
  fileHolder: File | null;

  constructor(
    private _FormBuilder: FormBuilder,
    private _HttpClient: HttpClient
  ) {
    this.fileHolder = null;
  }

  ngOnInit() {
    this.createQPForm = this._FormBuilder.group({
      qpName: ['', [Validators.required]],
      file: ['', [Validators.required]]
    });
  }

  onFileChange(event) {
    if (event.target.files && event.target.files.length) {
      this.fileHolder = event.target.files[0];
    }
  }

  createQP() {
    if (this.createQPForm.valid && this.fileHolder && this.fileHolder.name) {
      const formData: FormData = new FormData();
      formData.append('qpName', this.createQPForm.value.qpName);
      formData.append('file', this.fileHolder, this.fileHolder.name);
      // use the formDat here
    }
  }
}

请参阅此处的工作堆栈闪电战。


推荐阅读