I am trying to have a file upload feature in my React application but am running into a problem. When I try to upload a first picture, it works just fine. The file explorer dialog closes and my picture is displayed. Overwriting the picture with another picture from my file explorer also works.
However, when I cancel the file explorer while overwriting, I get the following error:
TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
Here is my relevant code:
showImage = (e) =>{
this.setState({image: URL.createObjectURL(e.target.files[0])})
}
render() {
return (
<div className="content">
<input
accept="image/*"
className="input"
id="icon-button-file"
type="file"
onChange={this.showImage}
/>
<label htmlFor="icon-button-file">
<IconButton
className="image"
aria-label="upload picture"
component="span"
>
{ this.state.image == null ? <AddAPhotoIcon className="icon" /> :
<img src={this.state.image} alt="test" className="picture"/> }
</IconButton>
</label>
</div>
)
I think the error means that the files array could be empty. You perhaps want to check if the array is empty before accessing a member.
if(e.target.files.length !== 0){
this.setState({image: URL.createObjectURL(e.target.files[0])})
}