繁体   English   中英

如何在 React 中显示保存为 blob 的图像

[英]How to display an image saved as blob in React

我写了一个 function 将图像保存为 blob:

render() {
  ...
  return (
    ...
      <input
        accept="image/*"
        onChange={this.handleUploadImage.bind(this)}
        id="contained-button-file"
        multiple
        type="file"
      />
)}

这是在 onChange 中调用的 function:

  handleUploadImage(event) {
    const that = this;
    const file = event.target.files[0];
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = () => {
      that.setState({
        image: URL.createObjectURL(file),
        userImage: reader.result,
      });
    };
  }

我认为这很好用,因为它保存在数据库中,因为文档有一个名为 image 的字段,如下所示: blob:http://localhost:3000/80953c91-68fe-4d2a-8f5e-d9dd437c1f94

这个 object 可以像this.props.product一样访问,访问图像是this.props.product.image

问题是当我想显示图像时,我不知道该怎么做。

我试图把它放在像这样的渲染中:

  {
    this.props.product.image ? (
      <img alt="" src={this.props.product.image} />
    ) : (
      null
    );
  }

它抛出这个错误:

在此处输入图像描述

和 header: 在此处输入图像描述

有什么建议么?

您应该尝试 URL.createObjectURL(blob)

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

myImage.src = URL.createObjectURL(blob);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM