mainak chakraborty
mainak chakraborty

Reputation: 664

ReactJS: Unable to render image in UI from REST API response

I have built a REST API that returns an image and I am successfully getting its response through PostMan agent. PostMan response In my React Code, I have this:

return fetch(url, sInit)
  .then((response) => {
    let blb = new Blob([response.body], { type: 'image/jpeg' });
    let fileUrl = (window.URL || window.webkitURL).createObjectURL(blb);
    window.open(fileUrl);
  })

The blob url generated does not have the image. What am I missing?

Upvotes: 0

Views: 909

Answers (1)

Fabian Schultz
Fabian Schultz

Reputation: 18546

You probably want to use the built-in blob() method by fetch:

fetch(
  'https://images.unsplash.com/35/SRkdurVYQFSFkMyHVwSu_spinnenweb-9536.jpg?dpr=2&auto=compress,format&fit=crop&w=376&h=251&q=80&cs=tinysrgb&crop='
)
  .then(res => res.blob())
  .then(blob => {
    let fileUrl = (window.URL || window.webkitURL).createObjectURL(blob);

    const img = document.createElement('img');
    img.src = fileUrl;
    document.querySelector('body').appendChild(img);
  });

Upvotes: 1

Related Questions