Untitled
user_6232722
plain_text
18 days ago
1.4 kB
1
Indexable
Never
import { NextRequest, NextResponse } from "next/server"; import { S3Client, PutObjectCommand, GetObjectCommand, } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; // Initialize the S3 client const Bucket = process.env.AMPLIFY_BUCKET; const s3 = new S3Client({ region: process.env.AWS_REGION, credentials: { accessKeyId: process.env.AWS_ACCESS_KEY_ID as string, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string, }, }); // Handle file upload (POST) export async function POST(request: NextRequest) { const formData = await request.formData(); const file = formData.get("file") as File; if (!file) { return NextResponse.json({ error: "No file uploaded" }, { status: 400 }); } try { const Body = (await file.arrayBuffer()) as Buffer; const uploadCommand = new PutObjectCommand({ Bucket, Key: file.name, Body }); await s3.send(uploadCommand); // Generate a signed URL for the uploaded file (expires in 1 hour) const getCommand = new GetObjectCommand({ Bucket, Key: file.name }); const signedUrl = await getSignedUrl(s3, getCommand, { expiresIn: 3600 }); return NextResponse.json({ message: "File uploaded successfully", signedUrl, }); } catch (error) { return NextResponse.json({ error: "File upload failed", details: error }, { status: 500 }); } }
Leave a Comment