63 lines
1.8 KiB
TypeScript
63 lines
1.8 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getFileByObjectName } from '@/lib/fileStorage'
|
|
import { prisma } from '@/lib/prisma'
|
|
import { withCors } from '@/lib/middleware'
|
|
|
|
async function handleDownload(req: NextRequest) {
|
|
try {
|
|
const pathSegments = req.nextUrl.pathname.split('/')
|
|
const fileIdIndex = pathSegments.indexOf('downloads') + 1
|
|
const fileId = pathSegments[fileIdIndex]
|
|
|
|
if (!fileId) {
|
|
return NextResponse.json({ error: '缺少文件ID' }, { status: 400 })
|
|
}
|
|
|
|
// 从数据库查找 objectName
|
|
let objectName: string | null = null
|
|
|
|
// 尝试从 Version 表查找
|
|
const version = await prisma.version.findFirst({
|
|
where: { fileId },
|
|
select: { objectName: true }
|
|
})
|
|
|
|
if (version) {
|
|
objectName = version.objectName
|
|
} else {
|
|
// 尝试从 Nssm 表查找
|
|
const nssm = await prisma.nssm.findFirst({
|
|
where: { fileId },
|
|
select: { objectName: true }
|
|
})
|
|
|
|
if (nssm) {
|
|
objectName = nssm.objectName
|
|
}
|
|
}
|
|
|
|
if (!objectName) {
|
|
return NextResponse.json({ error: '文件不存在' }, { status: 404 })
|
|
}
|
|
|
|
const file = await getFileByObjectName(objectName)
|
|
if (!file) {
|
|
return NextResponse.json({ error: '文件不存在' }, { status: 404 })
|
|
}
|
|
|
|
return new NextResponse(file.buffer, {
|
|
headers: {
|
|
'Content-Type': file.contentType || 'application/octet-stream',
|
|
'Content-Disposition': `attachment; filename=${file.filename || 'download'}`,
|
|
'Cache-Control': 'public, max-age=31536000',
|
|
}
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('下载失败:', error)
|
|
return NextResponse.json({ error: '下载失败' }, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export const GET = withCors(handleDownload)
|