---
title: HTTP Range 请求:断点续传与 206 Partial Content
keywords:
- Range
- 206 Partial Content
- Content-Range
- Accept-Ranges
- 断点续传
description: 说明 Range 请求与分块传输的语义,服务端返回 206 的要求、Content-Range 格式与 Accept-Ranges 启用,以及在大文件下载与媒体进度条中的实践。
categories:
- 文章资讯
- 编程技术
---
概述
Range 请求允许客户端只获取资源的部分字节范围,用于断点续传与媒体拖动。服务端需解析 Range 头并返回 206 Partial Content 与正确的 Content-Range。对不支持范围的资源返回 200 OK 或 416 Range Not Satisfiable。
示例:客户端请求与服务端响应
# 请求第 0–1023 字节
Range: bytes=0-1023
# 响应(部分内容)
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/123456
Accept-Ranges: bytes
Content-Length: 1024
Node.js 示例(简化)
import fs from 'node:fs'
import http from 'node:http'
http.createServer((req, res) => {
const stat = fs.statSync('big.mp4')
const range = req.headers['range']
res.setHeader('Accept-Ranges', 'bytes')
if (!range) {
res.writeHead(200, { 'Content-Length': stat.size, 'Content-Type': 'video/mp4' })
fs.createReadStream('big.mp4').pipe(res)
return
}
const match = /bytes=(\d*)-(\d*)/.exec(range)
let start = parseInt(match[1] || '0', 10)
let end = parseInt(match[2] || (stat.size - 1) + '', 10)
if (start > end || end >= stat.size) {
res.writeHead(416, { 'Content-Range': `bytes */${stat.size}` })
return res.end()
}
res.writeHead(206, {
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
'Content-Length': end - start + 1,
'Content-Type': 'video/mp4'
})
fs.createReadStream('big.mp4', { start, end }).pipe(res)
}).listen(8080)
工程建议
- 验证与安全:校验范围合法性;对异常情况返回
416与总长度;记录访问与速率限制。 - 媒体协作:视频音频支持范围有助于进度跳转;与缓存/CDN 配合保持一致。
- 可靠性:失败重试与并发分段下载需控制带宽与合并策略。
参考与验证
- RFC 7233 Range Requests:https://www.rfc-editor.org/rfc/rfc7233
- MDN Range 请求文档:https://developer.mozilla.org/docs/Web/HTTP/Range_requests

发表评论 取消回复