Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a JAX-RS method GET /reports/{id}/file that downloads a large PDF stored on disk so the browser saves it as report-42.pdf, without loading the file into memory.

We return Response.ok(entity, "application/pdf") where the entity is a StreamingOutput that runs Files.copy(path, outputStream), or simply the File, which the runtime streams for us, and we add the header Content-Disposition: attachment; filename="report-42.pdf" so the browser saves it under that name. Setting Content-Length lets clients show progress, and range support helps for very large files. Before opening anything, we check that the caller may see the report and answer 404 otherwise, and for non-ASCII names we add filename*=UTF-8''... as RFC 6266 describes.

Why this question is asked

Downloads look trivial until a 2 GB report is read into a byte array and the service runs out of memory, or until someone discovers they can download other customers' reports by changing a number in the URL. Interviewers ask this to see whether we know how to stream a response in JAX-RS and whether we think about the HTTP headers and security that make a download correct. In this answer, we will recap how browsers decide to save a file, write the endpoint, see why it uses constant memory, add authorization, handle file names properly and look at range requests for resumable downloads.

1A Quick Recap: What Makes a Browser Save a File

A browser decides what to do with a response from its headers. Content-Type: application/pdf says what the bytes are. Content-Disposition decides whether to display it or save it: inline means show it in the browser if possible, and attachment means save it, with the filename parameter suggesting the name. Content-Length tells the browser the total size, which is how it shows a progress bar and an estimated time.

So our job is to send the right headers and then the bytes, without holding the whole file in memory along the way.

2Writing the Endpoint

Here is the method. ReportService knows which reports a user may see and where each file is stored.

Java
@Path("reports")
public class ReportResource {
@Inject ReportService reports;
@Context SecurityContext security;
@GET
@Path("{id: \\d+}/file")
@Produces("application/pdf")
public Response download(@PathParam("id") long id) throws IOException {
Report report = reports.findVisibleTo(id, security.getUserPrincipal())
.orElseThrow(NotFoundException::new); // 404: missing or not yours
java.nio.file.Path file = report.storagePath();
long size = Files.size(file); // 2147483648 for a 2 GB file
StreamingOutput body = out -> Files.copy(file, out); // copies in small chunks
return Response.ok(body, "application/pdf")
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"report-" + id + ".pdf\"")
.header(HttpHeaders.CONTENT_LENGTH, size)
.build();
}
}
// GET /reports/42/file
// 200, Content-Type: application/pdf
// Content-Disposition: attachment; filename="report-42.pdf"
// Content-Length: 2147483648
Step throughStreaming a download
BrowserReportResourceRuntimeDisk
GET /reports/42/file
authorize, find file, read size
Response with StreamingOutput and headers
200, headers, Content-Length
call StreamingOutput.write(out)
Files.copy reads a chunk
chunk written, repeated until the end

7 messages in order. Play them, or step through them one at a time.

StreamingOutput is a callback interface. The runtime calls its write method after it has sent the status and headers, handing it the response output stream. Files.copy reads the file in small buffers and writes each one to the stream, so memory use stays at a few kilobytes no matter how big the file is. Returning a java.io.File as the entity works too, because the specification requires runtimes to support File and they stream it; some runtimes also accept java.nio.file.Path, so check your version.

3Why We Do Not Read the File Into Memory

The tempting version is Response.ok(Files.readAllBytes(file)). For a 2 GB file, that allocates a 2 GB byte array per request, and a Java array cannot even exceed about 2 GB, so the largest files fail outright. With ten users downloading at once, the service needs 20 GB of heap. Notice too that readAllBytes reads the whole file before sending the first byte, so the user waits for nothing to happen.

Streaming fixes all three problems: constant memory, no size ceiling and the first bytes leave immediately. The thread is still busy for the whole transfer, so for very high volumes we would serve files from object storage or a CDN instead, but for reports from a service, streaming is usually enough.

4Authorization Before Opening the File

The id in the URL is chosen by the client. If we look up the file by id alone, any logged-in user can try /reports/43/file, /reports/44/file and so on, which is called an insecure direct object reference. So the service method findVisibleTo loads the report only if it belongs to the caller or the caller has a role that allows it, and it does so before touching the file system.

We return 404 rather than 403 for someone else's report. A 403 would confirm that report 43 exists, which leaks information, while 404 treats reports you cannot see the same as reports that do not exist.

5Handling File Names Properly

The filename parameter is safest with plain ASCII characters, and we put it in double quotes. For names with other characters, such as a French report name containing U+00E9, RFC 6266 defines filename* with an explicit charset and percent-encoding, and modern browsers prefer it when both are present. We also remove quotes, slashes and control characters from any name we build from user data, so the header cannot be broken.

Java
String ascii = "rapport-42.pdf";
String encoded = URLEncoder.encode("rapport-\u00e9t\u00e9-42.pdf", StandardCharsets.UTF_8).replace("+", "%20");
String disposition = "attachment; filename=\"" + ascii + "\"; filename*=UTF-8''" + encoded;
// attachment; filename="rapport-42.pdf"; filename*=UTF-8''rapport-%C3%A9t%C3%A9-42.pdf

6Follow-up questions

How would you support resumable downloads?

By supporting HTTP range requests. The response advertises Accept-Ranges: bytes, and when a client resumes it sends Range: bytes=1048576-. The server then answers 206 Partial Content with Content-Range: bytes 1048576-2147483647/2147483648 and streams only that part, for example by opening a FileChannel and transferring from the offset. An ETag together with If-Range ensures the client does not join two different versions of the file. Some runtimes and servers offer range support for static files, but for a JAX-RS method we usually implement it ourselves or serve the file from object storage, which supports ranges natively.

What if the file is in object storage rather than on disk?

We can stream from the storage client's InputStream in the same StreamingOutput, or better, after authorization redirect the client to a short-lived pre-signed URL so the bytes never pass through our service.

What happens if the client disconnects halfway?

The write to the output stream fails with an IOException inside StreamingOutput. The runtime stops the response, and the try-with-resources or Files.copy closes the file. We should log it at a low level, because aborted downloads are normal.

7Conclusion

In this answer, we wrote a JAX-RS download that returns a StreamingOutput running Files.copy, with Content-Type application/pdf, Content-Disposition attachment and filename report-42.pdf, and Content-Length for progress. Streaming keeps memory constant and avoids the 2 GB array limit. We authorized the caller before opening the file and answered 404 for reports they cannot see, used filename* for non-ASCII names, and saw how range requests make large downloads resumable.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write a @GET method on reports/{id}/file with @Produces application/pdf. The first thing it does is authorization: load the report only if the current user may see it, and throw NotFoundException otherwise, so users cannot enumerate other people's reports and we do not reveal which ids exist.

Then, if they want more

Then I get the file's path and size and return Response.ok with a StreamingOutput entity whose write method is just Files.copy(path, out). That streams the file in small chunks after the headers are sent, so memory stays constant even for a multi-gigabyte file, unlike readAllBytes, which would allocate the whole file and fail beyond 2 GB.

Returning the File itself also works, since runtimes must stream File entities. I would add Content-Disposition: attachment; filename="report-42.pdf", which makes the browser save it with that name, and Content-Length with the file size so the browser can show progress.

If file names can contain non-ASCII characters, I add filename*=UTF-8'' with the percent-encoded name, as RFC 6266 describes, while keeping an ASCII fallback.

For very large files I would consider range support: Accept-Ranges bytes, and answering Range requests with 206 Partial Content and Content-Range, which makes downloads resumable, or I would serve the file from object storage with a pre-signed URL after the authorization check.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a JAX-RS method GET /reports/{id}/file that downloads a large PDF stored on disk...": https://scrivio-interview-library.netlify.app/java/jax-rs/69dc265d65/