58 lines
1.6 KiB
TypeScript
58 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { readFile } from 'fs/promises'
|
|
import { join } from 'path'
|
|
import { existsSync } from 'fs'
|
|
|
|
export async function GET(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ filename: string }> }
|
|
) {
|
|
try {
|
|
const { filename } = await params
|
|
|
|
// 构建文件路径
|
|
const filePath = join(process.cwd(), 'public', 'uploads', filename)
|
|
|
|
// 检查文件是否存在
|
|
if (!existsSync(filePath)) {
|
|
return new NextResponse('File not found', { status: 404 })
|
|
}
|
|
|
|
// 读取文件
|
|
const fileBuffer = await readFile(filePath)
|
|
|
|
// 根据文件扩展名设置 Content-Type
|
|
const ext = filename.split('.').pop()?.toLowerCase()
|
|
const contentTypeMap: Record<string, string> = {
|
|
// 图片
|
|
'jpg': 'image/jpeg',
|
|
'jpeg': 'image/jpeg',
|
|
'png': 'image/png',
|
|
'gif': 'image/gif',
|
|
'webp': 'image/webp',
|
|
'svg': 'image/svg+xml',
|
|
// 视频
|
|
'mp4': 'video/mp4',
|
|
'webm': 'video/webm',
|
|
'ogg': 'video/ogg',
|
|
'mov': 'video/quicktime',
|
|
'avi': 'video/x-msvideo',
|
|
'mkv': 'video/x-matroska',
|
|
}
|
|
|
|
const contentType = contentTypeMap[ext || ''] || 'application/octet-stream'
|
|
|
|
// 返回文件
|
|
return new NextResponse(fileBuffer, {
|
|
status: 200,
|
|
headers: {
|
|
'Content-Type': contentType,
|
|
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
},
|
|
})
|
|
} catch (error) {
|
|
console.error('读取文件失败:', error)
|
|
return new NextResponse('Internal Server Error', { status: 500 })
|
|
}
|
|
}
|