實現得獎資訊與資料庫整合
This commit is contained in:
74
app/api/upload/document/route.ts
Normal file
74
app/api/upload/document/route.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { writeFile, mkdir } from 'fs/promises'
|
||||
import { join } from 'path'
|
||||
import { existsSync } from 'fs'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const data = await request.formData()
|
||||
const file: File | null = data.get('file') as unknown as File
|
||||
const awardId = data.get('awardId') as string
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '沒有選擇文件' }, { status: 400 })
|
||||
}
|
||||
|
||||
// 驗證文件類型
|
||||
const allowedTypes = [
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.ms-powerpoint',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation'
|
||||
]
|
||||
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
return NextResponse.json({
|
||||
error: '不支持的文件格式,請上傳 PDF、DOC、DOCX、PPT、PPTX 格式的文件'
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
// 驗證文件大小 (10MB)
|
||||
const maxSize = 10 * 1024 * 1024
|
||||
if (file.size > maxSize) {
|
||||
return NextResponse.json({
|
||||
error: '文件大小超過 10MB 限制'
|
||||
}, { status: 400 })
|
||||
}
|
||||
|
||||
// 創建上傳目錄
|
||||
const uploadDir = join(process.cwd(), 'public', 'uploads', 'documents')
|
||||
if (!existsSync(uploadDir)) {
|
||||
await mkdir(uploadDir, { recursive: true })
|
||||
}
|
||||
|
||||
// 生成唯一文件名
|
||||
const timestamp = Date.now()
|
||||
const fileExtension = file.name.split('.').pop()
|
||||
const fileName = `${awardId}_${timestamp}.${fileExtension}`
|
||||
const filePath = join(uploadDir, fileName)
|
||||
|
||||
// 保存文件
|
||||
const bytes = await file.arrayBuffer()
|
||||
const buffer = Buffer.from(bytes)
|
||||
await writeFile(filePath, buffer)
|
||||
|
||||
// 返回文件信息
|
||||
const fileUrl = `/uploads/documents/${fileName}`
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
url: fileUrl,
|
||||
fileName: file.name,
|
||||
size: file.size,
|
||||
type: file.type
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('文件上傳錯誤:', error)
|
||||
return NextResponse.json(
|
||||
{ error: '文件上傳失敗' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user