概览通过在 Route Handlers 中解析 `Range` 请求头,返回 `206 Partial Content` 与 `Content-Range`,可实现断点下载与续传。Edge Runtime 适合流式输出与低延迟传输。app/api/download/route.tsexport const runtime = 'edge'
const SIZE = 10 * 1024 * 1024 // 10MB 示例
export async function GET(req: Request) {
const range = req.headers.get('range')
let start = 0
let end = SIZE - 1
if (range) {
const m = /bytes=(\d+)-(\d+)?/.exec(range)
if (m) {
start = Number(m[1])
end = m[2] ? Number(m[2]) : Math.min(start + 1024 * 256 - 1, SIZE - 1) // 默认 256KB 分块
}
}
const chunkSize = end - start + 1
const stream = new ReadableStream({
start(controller) {
// 这里用随机字节模拟实际文件读取
const buf = new Uint8Array(chunkSize)
crypto.getRandomValues(buf)
controller.enqueue(buf)
controller.close()
},
})
const status = range ? 206 : 200
const headers: Record<string, string> = {
'Content-Type': 'application/octet-stream',
'Accept-Ranges': 'bytes',
'Content-Length': String(chunkSize),
}
if (range) {
headers['Content-Range'] = `bytes ${start}-${end}/${SIZE}`
}
return new Response(stream, { status, headers })
}
客户端续传async function fetchChunk(url: string, start: number) {
const res = await fetch(url, { headers: { Range: `bytes=${start}-` } })
const ab = await res.arrayBuffer()
return new Uint8Array(ab)
}
治理要点实际场景使用存储读取(Blob/文件系统/对象存储),并做边界与合法性校验。设置 `Accept-Ranges: bytes` 并正确返回 `Content-Range` 与 `206` 状态码。与鉴权协同,避免未授权下载;记录断点与进度以便恢复。验证与指标浏览器与客户端:断点续传可靠;大文件传输更稳定Next.js:15.0+;Edge Runtime:稳定

发表评论 取消回复