Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

File Uploader #8

Merged
merged 9 commits into from
Jul 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions app/api/uploadthing/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createUploadthing, type FileRouter } from "uploadthing/next";
import { UploadThingError } from "uploadthing/server";

const f = createUploadthing();

const auth = (req: Request) => ({ id: "fakeId" }); // Fake auth function

// FileRouter for your app, can contain multiple FileRoutes
export const ourFileRouter = {
// Define as many FileRoutes as you like, each with a unique routeSlug
imageUploader: f({ image: { maxFileSize: "4MB" } })
// Set permissions and file types for this FileRoute
.middleware(async ({ req }) => {
// This code runs on your server before upload
const user = await auth(req);

// If you throw, the user will not be able to upload
if (!user) throw new UploadThingError("Unauthorized");

// Whatever is returned here is accessible in onUploadComplete as `metadata`
return { userId: user.id };
})
.onUploadComplete(async ({ metadata, file }) => {
// This code RUNS ON YOUR SERVER after upload
console.log("Upload complete for userId:", metadata.userId);

console.log("file url", file.url);

// !!! Whatever is returned here is sent to the clientside `onClientUploadComplete` callback
return { uploadedBy: metadata.userId };
}),
} satisfies FileRouter;

export type OurFileRouter = typeof ourFileRouter;
8 changes: 8 additions & 0 deletions app/api/uploadthing/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createNextRouteHandler } from "uploadthing/next";

import { ourFileRouter } from "./core";

// Export routes for Next App Router
export const { GET, POST } = createNextRouteHandler({
router: ourFileRouter,
});
15 changes: 12 additions & 3 deletions components/shared/EventForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { useRouter } from "next/navigation";
import { createEvent, updateEvent } from "@/lib/actions/event.actions";
import { IEvent } from "@/lib/database/models/event.model";
import Dropdown from "./Dropdown";
import { FileUploader } from "./FileUploader";

type EventFormProps = {
userId: string;
Expand All @@ -39,6 +40,8 @@ type EventFormProps = {
};

const EventForm = ({ userId, type, event, eventId }: EventFormProps) => {
const [files, setFiles] = useState<File[]>([]);

const initialValues =
event && type === "Update"
? {
Expand Down Expand Up @@ -116,16 +119,22 @@ const EventForm = ({ userId, type, event, eventId }: EventFormProps) => {
</FormItem>
)}
/>
{/* <FormField
<FormField
control={form.control}
name="imageUrl"
render={({ field }) => (
<FormItem className="w-full">
<FormControl className="h-72"></FormControl>
<FormControl className="h-72">
<FileUploader
onFieldChange={field.onChange}
imageUrl={field.value}
setFiles={setFiles}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/> */}
/>
</div>

<div className="flex flex-col gap-5 md:flex-grow">
Expand Down
68 changes: 68 additions & 0 deletions components/shared/FileUploader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/* eslint-disable react-hooks/exhaustive-deps */
"use client";

import { useCallback, Dispatch, SetStateAction } from "react";
// import type { FileWithPath } from "@uploadthing/react";
import { useDropzone } from "@uploadthing/react/hooks";
import { generateClientDropzoneAccept } from "uploadthing/client";

import { Button } from "@/components/ui/button";
import { convertFileToUrl } from "@/lib/utils";
import Image from "next/image";

type FileUploaderProps = {
onFieldChange: (url: string) => void;
imageUrl: string;
setFiles: Dispatch<SetStateAction<File[]>>;
};

export function FileUploader({
imageUrl,
onFieldChange,
setFiles,
}: FileUploaderProps) {
const onDrop = useCallback((acceptedFiles: File[]) => {
setFiles(acceptedFiles);
onFieldChange(convertFileToUrl(acceptedFiles[0]));
}, []);

const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: "image/*" ? generateClientDropzoneAccept(["image/*"]) : undefined,
});

return (
<div
{...getRootProps()}
className="flex-center bg-dark-3 flex h-72 cursor-pointer flex-col overflow-hidden rounded-xl bg-grey-50"
>
<input {...getInputProps()} className="cursor-pointer" />

{imageUrl ? (
<div className="flex h-full w-full flex-1 justify-center">
<Image
src={imageUrl}
alt="image"
width={250}
height={250}
className="w-full object-cover object-center"
/>
</div>
) : (
<div className="flex-center flex-col py-5 text-grey-500">
<Image
src="/assets/icons/upload.svg"
width={77}
height={77}
alt="file upload"
/>
<h3 className="mb-2 mt-2">Drag photo here</h3>
<p className="p-medium-12 mb-4">SVG, PNG, JPG</p>
<Button type="button" className="rounded-full">
Select from computer
</Button>
</div>
)}
</div>
);
}
6 changes: 6 additions & 0 deletions lib/uploadthing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { generateReactHelpers } from "@uploadthing/react/hooks";

import type { OurFileRouter } from "@/app/api/uploadthing/core";

export const { useUploadThing, uploadFiles } =
generateReactHelpers<OurFileRouter>();
63 changes: 62 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@stripe/stripe-js": "^2.2.1",
"@uploadthing/react": "^6.0.3",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"lucide-react": "^0.399.0",
Expand All @@ -33,7 +34,7 @@
"svix": "^1.24.0",
"tailwind-merge": "^2.3.0",
"tailwindcss-animate": "^1.0.7",
"uploadthing": "^6.13.2",
"uploadthing": "^6.0.4",
"zod": "^3.23.8"
},
"devDependencies": {
Expand Down