Resume a download or seek in media
This recipe shows how to fetch part of a file or page with Range: bytes=. Browsers and media players do this for you. The examples use curl so you can see what happens.
When to use this approach
Use a byte range to:
- continue a large download that stopped part-way
- read the start or end of a file without fetching all of it
- let a video or audio player jump to a point in a file
Check that the server offers it
A HEAD request shows the file's size and whether byte ranges are on offer:
curl -I https://example.com/talk.mp4
Look for Accept-Ranges: selector, bytes and a Content-Length.
Fetch the first part
curl -i -H "Range: bytes=0-1023" https://example.com/talk.mp4
The reply is 206 Partial Content. The Content-Range: bytes 0-1023/52428800 header says you got 1,024 bytes of 52,428,800.
Fetch the end of a file
curl -H "Range: bytes=-1024" -o tail.bin https://example.com/talk.mp4
A range with a minus sign first returns the last 1,024 bytes.
Resume a stopped download
If you have already saved 1,048,576 bytes in talk.mp4, ask for the rest:
curl -H "Range: bytes=1048576-" -o rest.bin https://example.com/talk.mp4
cat rest.bin >> talk.mp4
curl can do this for you with curl -C - -O https://example.com/talk.mp4.
To make sure the file did not change between attempts, send If-Range with the ETag from the first response:
curl -H 'Range: bytes=1048576-' -H 'If-Range: "9f2c..."' -o rest.bin https://example.com/talk.mp4
If the file changed, the server sends the whole new file with 200 instead of a part. Check the status before you join the pieces.
Seek in audio and video
A browser's media player sends Range: bytes= requests as the viewer drags the slider. You do not need to write code. Store the file as a binary file, for example by uploading it over WebDAV, and point a video or audio element at it.
Things to know
- The server may ignore a range and send the whole file with
200. Your client must cope. - A range that starts after the end of the file gets
416 Range Not Satisfiable, withContent-Range: bytes */<length>giving the real length. - A page the server composes has a weak
ETag, soIf-Rangeon a composed page always returns the whole page.
See also
- Byte ranges — every rule in full
- Accept-Ranges — the range units the server advertises