0

I am working on Sveltekit app using Typescript and want to display the images from R2, using workers R2 API, in the custom image component.

The following is the .svelte code

<script lang="ts">
  import { onMount } from 'svelte';

  export let filename: string;

  let srcName;
  let imageBlob: Blob;

  onMount(async () => {
    const response = await fetch('..<path to api>/api/gallery/media?filename=' + filename, {
      method: 'GET',
    });

    let responseJson = await response.json();

    console.log(responseJson);

    let img = new TextEncoder().encode(responseJson);

    imageBlob = new Blob([img.buffer]);

    srcName = URL.createObjectURL(imageBlob);
  });
</script>

<img src={srcName} alt="test" />

The API code

import { json } from "@sveltejs/kit";
import { CPInformation } from "$cplib/stores";

let cpInformation: any;
CPInformation.subscribe(value => cpInformation = value);

export async function GET({ url, platform }) {

  let filename = url.searchParams.get("filename");

  let imageFile = await platform.env.BK_COCKPIT.get(cpInformation.site_url + "/" + filename);

  let bod = await imageFile.body;

  //let imgBody = await imageFile.arrayBuffer();

  return json(bod)
};

Steps tried

Get the object as arrayBuffer.

1.

  • Convert to string using `new TextDecoder().decode(<object>) from API and pass to svelte file
  • Create blob on the svelte file after encoding the received string to arrayBuffer
  • CreateObjectURL from the blob

Result - blob is always empty

2.

  • From the blob above, create a file reader
  • This will generate the base64 URL
  • Link it to the src of img

Result - base64 image is of mime type image/octet or application/octet, despite declaring the {type: "image/jpeg"} while constructing the blob.

1 Answer 1

0

Change the API response to

return new Response(bod, {
    headers: {
      'content-type': imageFile.customMetadata['content-type'],
    }
  })

And in the svelte component, show the image as

let responseJson = await response.blob();
    srcName = URL.createObjectURL(responseJson);

Not the answer you're looking for? Browse other questions tagged or ask your own question.