Skip to content Skip to sidebar Skip to footer

Angular 5 File Upload: Failed To Set The 'value' Property On 'htmlinputelement'

I have a form for uploading a file in an angular 5 app, and as I have copied it exactly from a code I had written a while ago, I can swear it had worked before. Here is my HTML cod

Solution 1:

In my case I just removed the formControlName:

<input type="file" (change)="onFileChange($event)">

And .ts:

onFileChange(event) {
    const reader = new FileReader();

    if (event.target.files && event.target.files.length) {
      const [file] = event.target.files;
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.data.parentForm.patchValue({
          tso: reader.result
        });

        // need to run CD since file load runs outside of zonethis.cd.markForCheck();
      };
    }
  }

Solution 2:

Like the error is saying, you can only set an empty string to a file input value to clear the selection. It could open security risks otherwise. I can't imagine how that code could've ever worked. Maybe in some non-standard (bad) browser?

Shouldn't that code work if you just remove the line, why do you need to set the same value to the input that it already has anyway?

Edit: seems a custom ValueAccessor is needed for validating file inputs. Solution in another answer: Angular2: validation for <input type="file"/> won't trigger when changing the file to upload

Solution 3:

first of all you should remove "formControlName" from your element which type file, because it get's string then in your ts file you should add this

if (event.target.files && event.target.files.length > 0) {
  const file = (event.target.files[0] as File);
  this.yourForm.get('image').setValue(file);
  console.log(this.yourForm.get('image').value);
}

Solution 4:

Implement this by having 2 inputs for the file. Here is how I did it:

this.myForm= this.formBuilder.group({
      fileSource: ['', Validators.required],
      fileName: '',
    })

HTML

<input type="file" formControlName='fileSource' (change)="onFileSelected($event)"/>

Typescript

onFileSelected(event) {
    if(event.target.files.length > 0) 
     {
       this.myForm.patchValue({
          fileName: event.target.files[0],
       })
     }
  }

submit(){
    const formData = newFormData();
    formData.append('file', this.myForm.get('fileName').value);
   
    this.http.post('http://localhost:3000/upload', formData)
      .subscribe(res => {
        console.log(res);
        alert('Uploaded Successfully.');
      })
  }

Solution 5:

Do not set the value of the input property to the selected file. Instead just set the file content into a variable and append to the request object separately. For the file input , just assign the even.target.value as the input value, so the user see the actual file selected.

Post a Comment for "Angular 5 File Upload: Failed To Set The 'value' Property On 'htmlinputelement'"