2

I have a simple API that fetches an image, transforms it and is intended to return the new image. I can currently return a base64 string representation of the image, but how can I return this as an actual image that will simply render in the browser?

As an example, if I enter this link into the browser it correctly renders the image. I would like to be able to prefix this with my own URL (e.g. for testing https://localhost:3000/api/images/remote/[URL] and have it return the image in the same way.

Currently I can return the base64 string of the new image using the code below:

const response = await fetch(URL)

// do transformations

const arrayBuffer = await response.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
const base64 = buffer.toString("base64")

return base64

This results in a string that I can successfully render in an <img> tag as base64. How can I return this as an image object that will simply render in the browser, i.e. not as a base64 string?

I realise this may be as simple as correctly setting headers on the response and returning a blob, but I am drawing a blank when Googling (extensively).

Harry
  • 4,660
  • 7
  • 37
  • 65
  • Pretty much a matter of saving the file with the base64 I guess: https://stackoverflow.com/q/35940290/8816585 – kissu Oct 03 '22 at 08:41

1 Answers1

2

I assume you're referring to the /server directory in your nuxt project for your API? Because I needed a server-route for retrieving thumbnails that require an access token:

// file: ../server/api/thumbnail/[filename].get.js
export default defineEventHandler( async (e) => {
    const { filename } = e.context.params;

    try {
        const token = await getToken();

        const blob = await $fetch(`${BASE_URL}/resources/thumbnails/${filename}`, {
            headers: {
                "Token": token
            }
        });

        const arrayBuffer = await blob.arrayBuffer()
        const buffer = Buffer.from(arrayBuffer, 'base64')

        return buffer;
    }
    catch (err) {
        console.error(err);
    }

    return {};
});