简体   繁体   中英

Angular 4 : File Upload : Failed to set the 'value' property on 'HTMLInputElement'

 **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> 

When I'm selecting a file, it is giving me an error:

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.

I am new to Angular and am not able to find an other solution.

Can anyone explain me how to resolve this error?

You can hold the file in a variable in ts file and when submitting form use it:-

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

See the working stackblitz here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM