1

I want to fake a response. I have the base64 string data of a png image. Now I want to make a response but It does not work.

My code:

const data = "data:image/png;base64,iVBORw0KGgoAAAA...";
const res = new Response(data, {
      status: 200,
      statusText: "OK",
      headers: {
        "Content-Type": "image/png",
        "Content-Length": data.length
      },
    });

I did some research, and it seems like base64 can not just be passed to response body. It needs to be converted to a buffer or something like that.

It can be done in NodeJS like this Buffer.from(data, 'base64')

But my code is in the browser only.

Is there any way that I can implement this.

Tan Dat
  • 2,888
  • 1
  • 17
  • 39

2 Answers2

3

base64 is an encoded string, to get the actual image you need to convert it to binary data using atob. here is an example:

const b64String = data.split(',')[1];
var byteString = atob(b64String);
var arrayBuffer = new ArrayBuffer(byteString.length);
var intArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteString.length; i++) {
    intArray[i] = byteString.charCodeAt(i);
}
var imageBlob = new Blob([intArray], {type: 'image/png'});
const res = new Response(imageBlob, {
  status: 200,
  statusText: "OK",
  headers: {
    "Content-Type": "image/png",
    "Content-Length": imageBlob.size
  },
});
Quy Truong
  • 413
  • 3
  • 9
0

https://dev.to/ionic/converting-a-base64-string-to-a-blob-in-javascript-35kl

const base64Response = await fetch(`data:image/jpeg;base64,${base64Data}`);

easy as that.

And you can set additional headers by recreating the Response object and using the result of .blob() as body:

new Response(await base64Response.blob(), {
    status: 200,
    statusText: "OK",
    headers: {
        "Content-Type": "image/png",
        ...
    }
})
raythurnevoid
  • 2,652
  • 1
  • 25
  • 24