Search code examples
imagenext.jsblobfastapi

Can't display a blob image coming from FastAPI in Next JS


So I have my own API built with FastAPI that returns an image with

return Response(content=img_byte_arr.getvalue(), media_type="image/jpeg")

Everything works fine in the FastAPI Swagger UI as I can see the image

I have then a Next JS server action that correctly fetch the API with await fetch, get the blob and pass the ObjectURL to the client component with

const blob = await response.blob();
const imageBase64 = URL.createObjectURL(blob);
return imageBase64

Now the issue is that when I try to show the image on the client I got the error Not allowed to load local resource: blob:nodedata:3d26ac0d-f5fc-4161-a40f-2dfa21d3df1d even in my Vercel development env

I can't find understand why


Solution

  • At the end my solution was, on the server action pass the Blob into an arrayBuffer object

      const blob = await response.blob();
      let ab = await blob.arrayBuffer();
      let object = {
        image: Array.from(new Uint8Array(ab)),
        name: "image",
      };
    
      return object;
    

    On the client side, I've converted the arrayBuffer into a binary data and then created the imageURL

    const imageStringify = await requestImg(data);
    const binaryData = Buffer.from(imageStringify.image);
    
    const imageBase64 = URL.createObjectURL(
      new Blob([binaryData.buffer], { type: "image/jpeg" } /* (1) */)
    );