feat(file-streaming): add support for range requests in file streaming

This commit is contained in:
purocean
2025-01-02 14:49:04 +08:00
parent 4e0c0c8ad2
commit 5b16b97840
2 changed files with 24 additions and 1 deletions
+4
View File
@@ -182,6 +182,10 @@ export function read (repo: string, p: string): Promise<Buffer> {
return withRepo(repo, (_, targetPath) => fs.readFile(targetPath), p)
}
export function createReadStream (repo: string, p: string, options?: Parameters<typeof fs.createReadStream>[1]): Promise<ReturnType<typeof fs.createReadStream>> {
return withRepo(repo, async (_, targetPath) => fs.createReadStream(targetPath, options), p)
}
export function stat (repo: string, p: string) {
return withRepo(repo, async (_, targetPath) => {
const stat = await fs.stat(targetPath)
+20 -1
View File
@@ -230,7 +230,26 @@ const attachment = async (ctx: any, next: any) => {
noCache(ctx)
try {
ctx.body = await file.read(repo, path)
// support range
const range = ctx.headers.range
if (range) {
const { size } = await file.stat(repo, path)
const requestRange = range.replace('bytes=', '').split('-').map((x: string) => parseInt(x || '-1'))
const start = requestRange[0] < 0 ? 0 : requestRange[0]
const end = requestRange[1] < 0
? size - 1
: requestRange[1]
const chunkSize = end - start + 1
ctx.status = 206
ctx.set('Content-Range', `bytes ${start}-${end}/${size}`)
ctx.set('Accept-Ranges', 'bytes')
ctx.set('Content-Length', chunkSize)
ctx.body = await file.createReadStream(repo, path, { start, end })
} else {
ctx.body = await file.read(repo, path)
}
ctx.type = mime.getType(path)
} catch (error: any) {
if (error.code === 'ENOENT') {