Untitled
user_6232722
plain_text
a year ago
1.4 kB
10
Indexable
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 });
}
}
Editor is loading...
Leave a Comment