如何在浏览器中查看上传的图像 [重复]

Posted

技术标签:

【中文标题】如何在浏览器中查看上传的图像 [重复]【英文标题】: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来做到这一点?

【问题讨论】:

【参考方案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
    ]

【讨论】:

以上是关于如何在浏览器中查看上传的图像 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

上传前在浏览器中裁剪图像[关闭]

如何获取为浏览器上的文件输入选择的图像尺寸[重复]

在上传之前预览图像

如何在 Konvajs 画布中上传和加载图像?

存储在 Azure Blob 中的图像不会缓存在浏览器中

Django Ckeditor图像浏览器找不到图像