大文件下载要支持断点续传,处理 Range 请求头

要支持续传,响应先带 Accept-Ranges: bytes。

解析 Range 头里的起止字节,越界回 416。

命中片段返回 206,回 200 客户端会从头重下。

Content-Range 写清起止和文件总长。

没有 Range 头才走完整下载,并按总长回。

# 请求
GET /files/report.zip
Range: bytes=1024-2047

# 响应
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Range: bytes 1024-2047/10485760
Content-Length: 1024

# 服务端解析要点(伪代码)
rng = req.headers.get("Range")            # bytes=1024-2047
unit, _, spec = rng.partition("=")        # spec = "1024-2047"
s, _, e = spec.partition("-")
start = int(s or 0)
end   = int(e) if e else size - 1
if start >= size or end < start:
    return 416, {"Content-Range": "bytes */%d" % size}
length = end - start + 1                   # 按实际区间算,别信客户端跨度
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容