3

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).

1

1 Answer 1

3

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 {};
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.