Files
chinese-family-tree-2/app/api/upload/route.ts
T
freedakgmail e7167f4340 0.6.2.0
2025-12-10 13:03:10 +08:00

96 lines
2.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { writeFile, mkdir } from 'fs/promises'
import { join } from 'path'
import { existsSync } from 'fs'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
export async function POST(req: NextRequest) {
try {
// 验证用户登录
const session = await getServerSession(authOptions)
if (!session?.user?.id) {
return NextResponse.json({ error: '未授权' }, { status: 401 })
}
const formData = await req.formData()
const file = formData.get('file') as File
if (!file) {
return NextResponse.json({ error: '没有文件' }, { status: 400 })
}
// 验证文件类型(支持图片和视频)
const isImage = file.type.startsWith('image/')
const isVideo = file.type.startsWith('video/')
if (!isImage && !isVideo) {
return NextResponse.json({ error: '只能上传图片或视频文件' }, { status: 400 })
}
// 验证文件大小(图片限制 5MB,视频限制 100MB)
const maxImageSize = 5 * 1024 * 1024 // 5MB
const maxVideoSize = 100 * 1024 * 1024 // 100MB
const maxSize = isVideo ? maxVideoSize : maxImageSize
if (file.size > maxSize) {
return NextResponse.json({
error: isVideo ? '视频文件大小不能超过 100MB' : '图片文件大小不能超过 5MB'
}, { status: 400 })
}
// 读取文件内容
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
// 确保上传目录存在
const uploadDir = join(process.cwd(), 'public', 'uploads')
if (!existsSync(uploadDir)) {
await mkdir(uploadDir, { recursive: true })
}
// 生成唯一文件名
const timestamp = Date.now()
const randomStr = Math.random().toString(36).substring(2, 8)
// 从文件名或 MIME 类型获取扩展名
let ext = file.name.split('.').pop()?.toLowerCase()
if (!ext || ext === file.name) {
// 如果没有扩展名,从 MIME 类型推断
const mimeToExt: Record<string, string> = {
'image/jpeg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'image/webp': 'webp',
'image/svg+xml': 'svg',
'video/mp4': 'mp4',
'video/webm': 'webm',
'video/ogg': 'ogg',
'video/quicktime': 'mov',
'video/x-msvideo': 'avi',
'video/x-matroska': 'mkv',
}
ext = mimeToExt[file.type] || 'bin'
}
const fileName = `${timestamp}-${randomStr}.${ext}`
// 保存文件
const filePath = join(uploadDir, fileName)
await writeFile(filePath, buffer)
// 返回可访问的 URL
const url = `/uploads/${fileName}`
return NextResponse.json({
url,
fileName,
size: file.size,
type: file.type,
})
} catch (error) {
console.error('上传文件失败:', error)
return NextResponse.json(
{ error: '上传文件失败' },
{ status: 500 }
)
}
}