I am trying to convert the data retrieved from an API to a Blob
to be able to display it as an image on my page.
In the response, I get the data string which in the browser console looks like shown below. I assume that it is just a binary data of a file (it looks like it to me).
I use this code to convert the string to the Blob
:
const convertBinaryToBlob = (binary: string, contentType: string): Blob => {
const uInt8Array = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
uInt8Array[i] = binary.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
};
It gets generated fine, as well as the Blob
object URL, so I am able to put it as the src
of an image. The problem is that the image cannot be displayed by the browser because it contains some errors.
What's the issue in here? How am I able to get it working?
When I test it using curl
, I use this command:
curl -X 'GET' 'http://localhost:8000/images/file/6' -H 'accept: */*' --output img.png
The output file is working without any problem. Response headers from the curl
:
HTTP/1.1 200 OK
date: Tue, 25 Jan 2022 20:05:30 GMT
server: uvicorn
content-type: image/png
content-length: 3099363
last-modified: Sun, 23 Jan 2022 18:12:08 GMT
etag: 38e1bb48826eab759ab7220bc805124b