TypeError:无法在“URL”上执行“createObjectURL”:重载解析失败

问题描述 投票:0回答:3

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

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

TypeError:无法在“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>
)
javascript html reactjs image createobjecturl
3个回答
26
投票

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

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

0
投票

我也面临着类似的问题,这是因为由于安全原因,createObjectURL 现在已被贬值,我附上了一个 S.O.线程。

The URL.createObjectURL() method has been removed from the MediaStream  interface. This method has been deprecated in 2013 and superseded by  assigning streams to HTMLMediaElement.srcObject.  The old method was removed because it is less safe,  requiring a call to URL.revokeOjbectURL() to end the stream. Other user agents have either deprecated (Firefox) or removed (Safari) this feature feature.

试试这个方法:

const handelonchange = (e) => {
    const file = e.target.files[0];
    if(file) {
        const reader = new FileReader();
        reader.onloadend = () => {
            setimage(reader.result);
        }
        reader.readAsDataURL(file);
    }
}

<img src={image} />

中使用图像状态变量

线程”线程


-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]))})
}
© www.soinside.com 2019 - 2024. All rights reserved.