角度4:文件上传:无法在“ HTMLInputElement”上设置“ value”属性

时间:2019-05-10 11:41:46

标签: angular typescript

**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的新手,无法找到其他解决方案。

有人可以向我解释如何解决此错误吗?

1 个答案:

答案 0 :(得分:1)

您可以将文件保存在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
    }
  }
}

请参阅工作中的stackblitz here