【问题标题】:How to view an uploaded image in react in the browser [duplicate]如何在浏览器中查看上传的图像 [重复]
【发布时间】:2021-12-26 11:15:24
【问题描述】:

我有一个 react 前端,我想在上传图片时在浏览器上查看图片。 下面是我的上传功能

onDrop = async (files) => {

    const FILES = {
        "uploaded_image": [{
            name: files[0].name, <- Name prints on screen succesfully
            image: files[0].file, <- It is just empty
        }]
    }

    this.setState({
          ...some states
    })
   ..some calls
}

下面是渲染图

<div>
     <Image
     src={this.state.files[0].image}
     />
 </div>

图像显示如果我直接硬编码该字段,

image: require(`static_media/car.png`).default

但是我想在不硬编码的情况下显示上传文件的路径,我该如何修改onDrop中的image field来做到这一点?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    你需要使用 URL.createObjectURL(files[0])

     const FILES = {
        "uploaded_image": [{
            name: files[0].name, <- Name prints on screen succesfully
            image: URL.createObjectURL(files[0]), <- It is just empty
        }]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-05
      • 2010-12-25
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多