类型错误:无法在“URL”上执行“createObjectURL”:重载解析失败

Pim*_*v_h 3 html javascript image reactjs createobjecturl

我正在尝试在我的 React 应用程序中使用文件上传功能,但遇到了问题。当我尝试上传第一张图片时,它工作得很好。文件资源管理器对话框关闭并显示我的图片。用我的文件资源管理器中的另一张图片覆盖图片也有效。

但是,当我在覆盖时取消文件资源管理器时,出现以下错误:

类型错误:无法在“URL”上执行“createObjectURL”:重载解析失败。

这是我的相关代码:

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>
)
Run Code Online (Sandbox Code Playgroud)

小智 7

我认为该错误意味着文件数组可能为空。您可能想在访问成员之前检查数组是否为空。

if(e.target.files.length !== 0){
      this.setState({image: URL.createObjectURL(e.target.files[0])})
    }
Run Code Online (Sandbox Code Playgroud)