简体   繁体   中英

How to display an image saved as blob in React

I wrote a function that saves an image as blob:

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

and this is the function called in 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,
      });
    };
  }

I think this works fine because it saves in DB because the document has a field called image which looks like this: blob:http://localhost:3000/80953c91-68fe-4d2a-8f5e-d9dd437c1f94

this object can be accessed like this.props.product , to access the image it is this.props.product.image

The problem is when I want to show the image, I don't know how to do this.

I tried to put it in render like:

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

it throws this error:

在此处输入图像描述

and the header: 在此处输入图像描述

any suggestions?

You should try URL.createObjectURL(blob)

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

myImage.src = URL.createObjectURL(blob);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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