JRPG AddictJ
Convex Communityโ€ข15mo agoโ€ข
14 replies
JRPG Addict

How to get the URL of an image in the storage by its id?

I have tried the http method but obviously I'm doing something wrong.

convex/http.ts

import { httpRouter } from "convex/server";
import { Id } from "./_generated/dataModel";
import { httpAction } from "./_generated/server";
import { auth } from "./auth";

const http = httpRouter();

auth.addHttpRoutes(http);

http.route({
  path: "/getImage",
  method: "GET",
  handler: httpAction(async (ctx, request) => {
    const { searchParams } = new URL(request.url);
    const storageId = searchParams.get("storageId")! as Id<"_storage">;
    const blob = await ctx.storage.get(storageId);
    if (blob === null) {
      return new Response("Image not found", {
        status: 404,
      });
    }
    return new Response(blob);
  }),
});

export default http;


event-list.tsx

"use client";

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { api } from "@/convex/_generated/api";
import { useQuery } from "convex/react";
import Image from "next/image";

export default function EventList() {
  const events = useQuery(api.events.listEvents) || [];

  function getImageUrl({ storageId }: { storageId: string }) {
    const imageUrl = new URL(`${process.env.NEXT_PUBLIC_CONVEX_SITE_URL}/getImage`);
    imageUrl.searchParams.set("storageId", storageId);
    console.log(imageUrl.href);

    return imageUrl.href;
  }

  return (
          {events.map((event: any) => (
            <Card key={event._id}>
              <CardContent className="p-4">
                <Image
                  src={getImageUrl(event.imageId)}
                  alt={event.title}
                  width={300}
                  height={200}
                  className="mb-4 h-48 w-full rounded object-cover"
                />
              </CardContent>
            </Card>
          ))}
  );
}
Was this page helpful?