【问题标题】:How to display an image saved as blob in React如何在 React 中显示保存为 blob 的图像
【发布时间】:2020-09-22 14:52:35
【问题描述】:

我写了一个将图像保存为 blob 的函数:

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

这是 onChange 中调用的函数:

  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,
      });
    };
  }

我认为这很好用,因为它保存在 DB 中,因为文档有一个名为 image 的字段,看起来像这样:blob:http://localhost:3000/80953c91-68fe-4d2a-8f5e-d9dd437c1f94

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

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

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

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

它会抛出这个错误:

和标题:

有什么建议吗?

【问题讨论】:

  • 你试过渲染base64中的图片源吗?
  • 附带说明:onChange={this.handleUploadImage.bind(this)} 将在每次渲染时创建一个新函数。您可以通过在组件的构造函数中仅绑定一次来优化它。
  • @haensl 我只尝试了我在问题中提出的方式。应该怎么渲染成这样? btoa?
  • &lt;img alt="" src={btoa(this.props.product.image)} /&gt;
  • 如果我没记错的话,出于安全考虑,您不能使用本地文件。但如果这是原因,这将记录在控制台中。

标签: javascript reactjs blob filereader


【解决方案1】:

你应该试试 URL.createObjectURL(blob)

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

myImage.src = URL.createObjectURL(blob);

【讨论】:

  • 成功了! , 另一个重要的事情是如果使用 axios 则在请求中添加responseType: "blob"
猜你喜欢
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
  • 2012-01-16
  • 1970-01-01
  • 2021-12-06
  • 2022-01-24
  • 2020-01-09
相关资源
最近更新 更多