0

We have a problem with showing in browser (actually Chrome) binary images receiving from REST backend API. The backend REST endpoint defined in Java like this

@GetMapping(path = "/images/{imageId:\\d+}/data", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getImageData(@PathVariable long imageId) {
    return ... skipped ...
}

On the frontend we do these steps:

  1. request image data via fetch JS method call
    async function getImage(id) {
        return await fetch(`${URL}/images/${id}/data`, {
            method: 'GET',
            headers: new Headers(HEADERS)
        }).then(response => {
             return response.text();
        });
    }
  1. thus on frontend we have raw binary image data in this format (so far so good - it's really JPEG binary data). Attached the source JPEG

https://www.dropbox.com/s/8mh6xz881by5lu1/0gCrmsLkgik.jpg?dl=0

  1. then we call this code to receive base64 encoded image
    let reader = new FileReader();
        reader.addEventListener('loadend', event => {
        console.log(event.srcElement.result)
    });

    reader.readAsDataURL(new Blob([data]));
  1. as a result we have something looks like base64 encoded data

https://www.dropbox.com/s/uvx042j2dgizkr9/base64.txt?dl=0

  1. we tried to put base64 encoded data into <img> element without any success :(

So the question is how to receive on frontend correct base64 images for browser showing? What we do wrong?

Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41

1 Answers1

1

Here's some working code, based on this example and the @somethinghere's comment above. Pay attention to how the response is handled in getImage:

function getImage(id) {
    return fetch(`https://placekitten.com/200/140`, {
        method: 'GET',
    }).then(response => {
        return response.blob(); // <- important
    });
}

async function loadAndDisplay() {
    let blob = await getImage();
    let imageUrl = URL.createObjectURL(blob);
    let img = document.createElement('img');
    img.src = imageUrl;
    document.body.appendChild(img)
}

loadAndDisplay()

That said, a much simpler option would be just to insert a tag like <img src=/images/id/data> and leave all loading/displaying to the browser. In this case your backend has to provide the correct content-type though.

georg
  • 211,518
  • 52
  • 313
  • 390