Files
backerup-website/frontend/app/api/files/[token]/download/route.ts
T
Anders Böttcher 50566f2a22 Initial Commit
2026-05-11 23:39:16 +02:00

40 lines
1.1 KiB
TypeScript

import { NextResponse } from 'next/server'
import { getFile, getUploadPath } from '@/lib/store'
import fs from 'fs'
export async function GET(
_request: Request,
{ params }: { params: Promise<{ token: string }> },
) {
const { token } = await params
const record = await getFile(token)
if (!record) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const filePath = getUploadPath(token, record.originalName)
if (!fs.existsSync(filePath)) {
return NextResponse.json({ error: 'File missing on disk' }, { status: 404 })
}
const stream = fs.createReadStream(filePath)
const webStream = new ReadableStream({
start(controller) {
stream.on('data', (chunk) => controller.enqueue(chunk))
stream.on('end', () => controller.close())
stream.on('error', (err) => controller.error(err))
},
cancel() {
stream.destroy()
},
})
return new Response(webStream, {
headers: {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename="${record.originalName}"`,
'Content-Length': String(record.size),
},
})
}