Files
record-app-next/app/api/upload/presign/route.ts
2025-07-31 17:05:07 +08:00

51 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { NextRequest } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
const s3 = new S3Client({
region: process.env.AWS_REGION || "us-east-1",
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
},
});
export async function POST(req: NextRequest) {
try {
// 验证用户身份
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
return Response.json({ error: "未授权" }, { status: 401 });
}
const { fileName, fileType } = await req.json();
if (!fileName || !fileType) {
return Response.json({ error: "缺少必要参数" }, { status: 400 });
}
// 生成唯一的文件名包含用户ID和时间戳
const userId = session.user.id || session.user.email;
const timestamp = Date.now();
const uniqueFileName = `recordings/${userId}/${timestamp}-${fileName}`;
const command = new PutObjectCommand({
Bucket: process.env.AWS_S3_BUCKET!,
Key: uniqueFileName,
ContentType: fileType,
});
const url = await getSignedUrl(s3, command, { expiresIn: 300 }); // 5分钟有效
return Response.json({
url,
fileName: uniqueFileName,
});
} catch (error) {
console.error("生成上传凭证失败:", error);
return Response.json({ error: "生成上传凭证失败" }, { status: 500 });
}
}