9

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?

Leo Messi
  • 5,157
  • 14
  • 63
  • 125
  • Have you tried rendering the image source in [base64](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa)? – Haensl Jun 03 '20 at 19:19
  • 1
    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. – Haensl Jun 03 '20 at 19:21
  • @haensl I only tried the way I presented in the question. How should it be rendered like that? with `btoa`? – Leo Messi Jun 03 '20 at 19:21
  • 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. – japrescott Jun 03 '20 at 19:23

1 Answers1

11

You should try URL.createObjectURL(blob)

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

myImage.src = URL.createObjectURL(blob);
grzim
  • 534
  • 3
  • 10
  • 2
    Worked! , another important thing is to add `responseType: "blob"` to the request if using axios – llermaly Apr 17 '21 at 21:28
  • 1
    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 https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL – M. Elghamry Jul 26 '22 at 16:56