16

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>
)
Pimv_h
  • 380
  • 1
  • 3
  • 13

2 Answers2

24

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])})
    }
yourivdloo
  • 364
  • 2
  • 16
-1
 dataURLToBlob(dataurl) {
        let arr = dataurl.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
    },
 showImage = (e) =>{
   this.setState({image: URL.createObjectURL(dataURLToBlob(e.target.files[0]))})
}
sri harsha
  • 676
  • 6
  • 16
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 20 '21 at 04:18