Implementing HTTP Range (Partial Content) Downloads with SpringBoot

This article explains why large file downloads can fail on unstable networks, how to use HTTP Range headers and status codes for resumable downloads, and provides a complete SpringBoot implementation—including controller, service logic, and range‑parsing code—to enable reliable partial content delivery.

Top Architect
Top Architect
Top Architect
Implementing HTTP Range (Partial Content) Downloads with SpringBoot

Introduction

Internet connections can be slow and unstable, causing large object downloads to fail when the network disconnects. Using the Range request header allows a client to specify the byte range it needs, enabling resumable downloads.

How HTTP Range Works

Clients include a Range header (e.g., bytes=0-499) in a GET request. Servers indicate support via the Accept‑Ranges response header. If the request is valid, the server returns 206 Partial Content with a Content‑Range header; otherwise it may return 416 Requested Range Not Satisfiable or 200 OK (no range support).

curl -i --range 0-9 http://localhost:8080/file/chunk/download

Typical response headers for a successful range request:

HTTP/1.1 206
Accept-Ranges: bytes
Content-Range: bytes 0-9/13485
Content-Length: 10

Key Points

HTTP/1.1 and later support range requests; older versions do not.

Check the Accept‑Ranges header to confirm support.

Specify the desired byte range with the Range header.

Servers indicate the returned range with Content‑Range and its length with Content‑Length.

Use If‑Range together with ETag or Last‑Modified to verify resource freshness.

Range Header Syntax

Range: bytes=0-499

– first 500 bytes. Range: bytes=500-999 – next 500 bytes. Range: bytes=-500 – last 500 bytes. Range: bytes=500- – from byte 500 to the end. Range: bytes=0- – the whole file.

Handling Illegal Ranges

Invalid range specifications (e.g., wrong unit, out‑of‑bounds values) cause the server to ignore the range and return the full content with a 200 OK status.

Range: byte=0-499   // error: should be "bytes"
Range: bytes=0-1000 // error: end exceeds file size
Range: bytes=1000-2000 // error: start exceeds file size

SpringBoot Implementation

Controller

@Slf4j
@RestController
public class Controller {
    @Autowired
    private FileService fileService;

    /** Download file with optional range */
    @GetMapping("/oceanfile/download")
    public void downloadOceanfile(@RequestParam String fileId,
                                  @RequestHeader(value = "Range", required = false) String range,
                                  HttpServletResponse response) {
        this.fileService.downloadFile(fileId, response, range);
    }
}

Service

@Slf4j
@Service
public class FileService {
    @Autowired
    private CephUtils cephUtils;

    /** Download whole file or a byte range */
    public void downloadFile(String fileId, HttpServletResponse response, String range) {
        FileInfo fileInfo = getFileInfo(fileId);
        String bucketName = fileInfo.getBucketName();
        String relativePath = fileInfo.getRelativePath();
        RangeDTO rangeInfo = executeRangeInfo(range, fileInfo.getFileSize());
        if (Objects.isNull(rangeInfo)) {
            cephUtils.downloadFile(response, bucketName, relativePath);
            return;
        }
        cephUtils.downloadFileWithRange(response, bucketName, relativePath, rangeInfo);
    }

    private RangeDTO executeRangeInfo(String range, Long fileSize) {
        if (StringUtils.isEmpty(range) || !range.contains("bytes=") || !range.contains("-")) {
            return null;
        }
        long startByte = 0;
        long endByte = fileSize - 1;
        range = range.substring(range.lastIndexOf('=') + 1).trim();
        String[] ranges = range.split("-");
        if (ranges.length == 0 || ranges.length > 2) {
            return null;
        }
        try {
            if (ranges.length == 1) {
                if (range.startsWith("-")) {
                    // bytes=-500 -> last 500 bytes
                    endByte = Long.parseLong(ranges[0]);
                } else if (range.endsWith("-")) {
                    // bytes=500- -> from 500 to end
                    startByte = Long.parseLong(ranges[0]);
                }
            } else {
                // bytes=1024-2048
                startByte = Long.parseLong(ranges[0]);
                endByte = Long.parseLong(ranges[1]);
            }
        } catch (NumberFormatException e) {
            startByte = 0;
            endByte = fileSize - 1;
        }
        if (startByte >= fileSize) {
            log.error("range error, startByte >= fileSize. startByte: {}, fileSize: {}", startByte, fileSize);
            return null;
        }
        return new RangeDTO(startByte, endByte);
    }
}

The above code demonstrates how to parse the Range header, validate the requested byte positions, and delegate to a storage utility (e.g., Ceph) to stream either the whole file or the specified segment.

JavaHTTPFile DownloadSpringBootRange RequestsPartial Content
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.