How to display an image saved as blob in React
Asked Answered
I

1

11

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?

Illfounded answered 3/6, 2020 at 19:6 Comment(5)
Have you tried rendering the image source in base64?Allness
On a side note: onChange={this.handleUploadImage.bind(this)} will create a new function on every render. You can optimise this by only binding once in the constructor of your component.Allness
@haensl I only tried the way I presented in the question. How should it be rendered like that? with btoa?Illfounded
<img alt="" src={btoa(this.props.product.image)} />Allness
if I remember correctly, you cannot use local files because of security concerns. but this would be logged in the console if that would be the reason.Classieclassification
I
16

You should try URL.createObjectURL(blob)

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

myImage.src = URL.createObjectURL(blob);
Inutile answered 3/6, 2020 at 19:47 Comment(2)
Worked! , another important thing is to add responseType: "blob" to the request if using axiosGreathouse
It is worth noting that you should -have to- revoke the object when not needed especially in single page applications where the document isn't unloaded for an extended period of time. Refer to developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURLFinding

© 2022 - 2024 — McMap. All rights reserved.