Ana Jentel
Ana Jentel

Reputation: 89

upload image file to state with react

I am trying to upload an image with react with this code

<input type="file" id="InputFile" accept="image/*" value={this.state.image} onChange={this.handelChangeImage} />

this is the state

constructor(props) {
super(props);
this.state = {
    image: [],
}

this.handelChangeImage = this.handelChangeImage.bind(this);

}

and this is the binding function

handelChangeImage(event) {
   let image = event.target.files[0];
   let form = new FormData();
   form.append('image', image);
   this.setState({
       image: form,
   });

}

it gives me that error

Uncaught 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.

any help!!

Upvotes: 3

Views: 5777

Answers (2)

Ana Jentel
Ana Jentel

Reputation: 89

My error was here

<input type="file" id="InputFile" accept="image/*" value={this.state.image} onChange={this.handelChangeImage} />

I have to remove this value={this.state.image}

Upvotes: 3

Tiago Alves
Tiago Alves

Reputation: 2316

Looks like you are not reading your file properly, try something like:

handelChangeImage(event) {
  const reader = new FileReader();
  reader.onload = function(ee) {
    this.setState({fileData: ee.target.result});
  }.bind(this);
}

You can find more info about FileReader here.

Upvotes: -1

Related Questions