返回 presentation-ai
core.ts
根目录 / src / app / api / uploadthing / core.ts
1 import { auth } from "@/server/auth";
2 import "server-only";
3 import { createUploadthing, type FileRouter } from "uploadthing/next";
4 import { UploadThingError, UTApi } from "uploadthing/server";
5
6 const f = createUploadthing();
7
8 export const utapi = new UTApi();
9 // FileRouter for your app, can contain multiple FileRoutes
10 export const ourFileRouter = {
11 // Define as many FileRoutes as you like, each with a unique routeSlug
12 imageUploader: f({ image: { maxFileSize: "4MB" } })
13 // Set permissions and file types for this FileRoute
14 .middleware(async () => {
15 // This code runs on your server before upload
16 const session = await auth();
17
18 console.log(session);
19 // If you throw, the user will not be able to upload
20 if (!session) throw new UploadThingError("Unauthorized");
21
22 // Whatever is returned here is accessible in onUploadComplete as `metadata`
23 return { userId: session.user.id };
24 })
25 .onUploadComplete(async ({ metadata, file }) => {
26 // This code RUNS ON YOUR SERVER after upload
27 console.log("Upload complete for userId:", metadata.userId);
28
29 console.log("file url", file.url);
30
31 // !!! Whatever is returned here is sent to the clientside `onClientUploadComplete` callback
32 return { uploadedBy: metadata.userId };
33 }),
34 editorUploader: f({
35 image: { maxFileSize: "4MB" },
36 pdf: { maxFileSize: "16MB" },
37 text: { maxFileSize: "16MB" },
38 video: { maxFileSize: "64MB" },
39 })
40 .middleware(async () => {
41 const session = await auth();
42 if (!session) throw new UploadThingError("Unauthorized");
43 return { userId: session.user.id };
44 })
45 .onUploadComplete(async ({ file }) => {
46 // Simply return the file URL and name
47 return {
48 key: file.key,
49 name: file.name,
50 size: file.size,
51 type: file.type,
52 url: file.ufsUrl,
53 };
54 }),
55 fontUploader: f({
56 image: { maxFileSize: "4MB" },
57 text: { maxFileSize: "2MB" },
58 })
59 .middleware(async () => {
60 const session = await auth();
61 if (!session) throw new UploadThingError("Unauthorized");
62 return { userId: session.user.id };
63 })
64 .onUploadComplete(async ({ file }) => {
65 const familyName = file.name.replace(/\.[^.]+$/, "");
66 return { familyName };
67 }),
68 } satisfies FileRouter;
69
70 export type OurFileRouter = typeof ourFileRouter;
71
71 lines TYPESCRIPT