added file upload and storage

This commit is contained in:
2025-07-11 14:21:51 -04:00
parent 14cbbccd3a
commit 31ce343566
8 changed files with 240 additions and 2 deletions

View File

@@ -0,0 +1,85 @@
'use client'
import React, { useState, DragEvent } from 'react'
export default function UploadTestPage() {
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [uploading, setUploading] = useState(false)
const [message, setMessage] = useState('')
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] || null
setSelectedFile(file)
setMessage('')
}
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault()
const file = e.dataTransfer.files?.[0]
if (file) {
setSelectedFile(file)
setMessage('')
}
}
const handleUpload = async () => {
if (!selectedFile) return
const formData = new FormData()
formData.append('file', selectedFile)
setUploading(true)
setMessage('')
try {
const res = await fetch('/api/files/upload', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) throw new Error(data.message || 'Upload failed')
setMessage(`✅ File uploaded: ${data.filename || selectedFile.name}`)
setSelectedFile(null)
} catch (err: any) {
setMessage(`❌ Upload failed: ${err.message}`)
} finally {
setUploading(false)
}
}
return (
<div className="max-w-md mx-auto mt-10 p-6 bg-white rounded shadow space-y-4">
<h2 className="text-xl font-semibold">File Upload Test</h2>
{/* Drag and drop area */}
<div
onDrop={handleDrop}
onDragOver={e => e.preventDefault()}
className="border-2 border-dashed border-gray-400 rounded p-6 text-center cursor-pointer bg-gray-50 hover:bg-gray-100"
>
{selectedFile ? (
<p>{selectedFile.name}</p>
) : (
<p>Drag & drop a file here or click below to select</p>
)}
</div>
{/* File input */}
<input type="file" onChange={handleFileChange} className="block" />
{/* Upload button */}
<button
onClick={handleUpload}
className="btn btn-primary"
disabled={!selectedFile || uploading}
>
{uploading ? 'Uploading...' : 'Upload'}
</button>
{/* Upload result */}
{message && <p className="text-sm">{message}</p>}
</div>
)
}

View File

@@ -0,0 +1,86 @@
import { getServerSession } from "next-auth";
import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "../../auth/[...nextauth]/route";
import { canUploadOrViewFiles } from "@/lib/auth/checkRole";
import { v4 as uuidv4 } from 'uuid';
import path from "path";
import { mkdirSync, existsSync, writeFileSync } from 'fs';
import { prisma } from "@/lib/prisma";
const MAX_SIZE_MB = parseInt(process.env.UPLOAD_FILE_SIZE || '10', 10);
const MAX_SIZE_BYTES = MAX_SIZE_MB * 1024 * 1024;
// Ensure it's relative to project root
const UPLOAD_DIR = path.join(process.cwd(), 'data/uploads');
export const config = {
api: {
bodyParser: false,
},
};
export async function POST(req: NextRequest) {
const session = await getServerSession(authOptions);
const user = session?.user;
if (!user || !canUploadOrViewFiles(user.role)) {
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
}
try {
const formData = await req.formData();
const file = formData.get("file") as File | null;
const eventId = formData.get("eventId") as string | null;
if (!file) {
return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
}
if (file.size > MAX_SIZE_BYTES) {
return NextResponse.json({ error: `File exceeds ${MAX_SIZE_MB}MB` }, { status: 400 });
}
const allowedTypes = ["application/pdf", "image/jpeg", "image/png", "text/plain"];
if (!allowedTypes.includes(file.type)) {
return NextResponse.json({ error: "Unsupported file type" }, { status: 400 });
}
// Ensure uploads directory exists
if (!existsSync(UPLOAD_DIR)) {
mkdirSync(UPLOAD_DIR, { recursive: true });
}
// Create unique filename
const safeFileName = `${uuidv4()}-${file.name}`;
const fullPath = path.join(UPLOAD_DIR, safeFileName);
const arrayBuffer = await file.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
writeFileSync(fullPath, buffer);
// Save metadata in DB
const saved = await prisma.fileUpload.create({
data: {
filename: file.name,
filepath: fullPath,
filetype: file.type,
filesize: file.size,
uploadedBy: {
connect: { email: user.email! },
},
event: eventId ? {
connect: { id: eventId }
} : undefined,
},
});
return NextResponse.json({
message: "File uploaded successfully",
file: saved,
}, { status: 201 });
} catch (error) {
console.error("File upload error:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}