#http endpoint to upload file and return url
4 messages · Page 1 of 1 (latest)
Hi @keen flower. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Certainly! Here’s a simple HTTP endpoint using Convex that accepts any file, stores it in Convex storage, and returns a URL to access the file.
1. Define the HTTP Action
Create a file (e.g., convex/http.ts) and add the following code:
import { httpRouter } from "convex/server";
import { httpAction } from "./_generated/server";
const http = httpRouter();
http.route({
path: "/upload",
method: "POST",
handler: httpAction(async (ctx, request) => {
// Step 1: Read the file from the request body
const blob = await request.blob();
// Step 2: Store the file in Convex storage
const storageId = await ctx.storage.store(blob);
// Step 3: Generate a URL to access the file
const url = await ctx.storage.getUrl(storageId);
// Step 4: Return the URL as JSON
return new Response(JSON.stringify({ url }), {
status: 200,
headers: {
"Content-Type": "application/json",
// Add CORS headers if needed
"Access-Control-Allow-Origin": "*",
},
});
}),
});
export default http;
This endpoint:
- Accepts any file via a POST request.
- Stores the file in Convex storage.
- Returns a JSON response with the file’s URL.
2. (Optional) Handle CORS Preflight
If you need to support CORS, add an OPTIONS handler as shown in the docs:
http.route({
path: "/upload",
method: "OPTIONS",
handler: httpAction(async (_, request) => {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "86400",
},
});
}),
});