Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

enter image description here

and the header: enter image description here

any suggestions?

like image 243
Leo Messi Avatar asked Jun 03 '20 19:06

Leo Messi


People also ask

How do I display image data in React?

To display binary data as image in React, we can set the src prop of the img element to a base64 URL.

How do I convert a blob file to an image?

getContext("2d"); // Get the "context" of the canvas var img = document. getElementById("myimage"); // The id of your image container ctx. drawImage(img,0,0,width,height); // Draw your image to the canvas var jpegFile = canvas. toDataURL("image/jpeg"); // This will save your image as a //jpeg file in the base64 format.


1 Answers

You should try URL.createObjectURL(blob)

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

myImage.src = URL.createObjectURL(blob);
like image 73
grzim Avatar answered Nov 03 '22 01:11

grzim