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

How to display an image saved as blob in React

我写了一个将图像保存为 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,
      });
    };
  }

我认为这很好用,因为它保存在数据库中,因为文档有一个名为图像的字段,如下所示: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);