Sveltekit project how to get images from endpoint

Viewed 141

I'm creating a simple Blog to exploring Sveltekit and how it works.

I created an endpoint to manage the Upload of an image, which is stored in a folder placed in the root folder (same level of src).

Now I'm trying to get this image and shows in the front end when the post is loaded. It's pretty simple but I can't manage how to do it. In Nodejs normally I create an API to serve the image when is called like (ex. the API url is /api/v1/images/):

function get(req, res, next) {
    ...
    var fileStream = fs.createReadStream(imagePath);
    res.writeHead(200, { "Content-Type": "image/" + extensionName });
    fileStream.pipe(res);
    ...
}

In the frontend I call it:

<img src={getImageFromBackend("example.jpg")} alt="Example" />

But in Sveltekit I can't do the same.

Any ideas?

Thanks

1 Answers

You should create another endpoint that serves the image. The endpoint will look like this:

import {promises as fs} from "fs";

export async function get() {
    const asset = await fs.readFile("sample.jpg");
    return {
        headers: {
            "Content-Type": "image/jpeg"
        },
        body: asset
    };
}
Related