Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a Spring MVC endpoint that returns a generated PDF report as a download named report-2026-11.pdf. Which headers matter, and how do you avoid holding a large file fully in memory?

We return ResponseEntity<Resource> (or a StreamingResponseBody) with Content-Type application/pdf and a Content-Disposition header built with ContentDisposition.attachment().filename("report-2026-11.pdf").build(), and we set Content-Length when we know the size so the browser can show progress, leaving it out for streamed content. For large files we stream from disk or object storage, with FileSystemResource (which also supports Range requests in Spring MVC), InputStreamResource or StreamingResponseBody, instead of building a byte[]. Non-ASCII filenames need filename* encoding, which ContentDisposition produces when given a charset, and we always check that the user may see this file and never build paths from unvalidated input.

Why this question is asked

Downloading a generated report is one of the most common endpoints in business applications, and also one that is easy to get subtly wrong. A missing header makes the browser open the PDF in a tab instead of saving it with the right name, a byte array makes memory grow with every concurrent download, and a path built from a request parameter lets someone download another customer's report. Interviewers ask this question to check that we know the headers and the Spring types that stream. In this answer, we will recap the headers that control a download, write the endpoint, compare ways of producing the body without holding it in memory, handle non-ASCII filenames, look at Range requests, and secure the endpoint.

1A Quick Recap of the Headers That Matter

Three response headers decide how a browser handles a download. Content-Type tells it what the bytes are; for a PDF it is application/pdf, which lets the browser pick the right viewer or icon. Content-Disposition tells it what to do: attachment means save it as a file, inline means display it, and the filename parameter suggests the name to save it under. Content-Length tells it the total size in bytes, which the browser uses to show a progress bar and an estimated time.

Two more headers appear in good download endpoints. Cache-Control decides whether a report with private data may be cached (private, or no-store for sensitive reports), and Accept-Ranges: bytes tells the client it may request parts of the file, which download managers and PDF viewers use to resume or to load pages on demand.

Download headers
HeaderExample valueEffect
Content-Typeapplication/pdfbrowser knows it is a PDF
Content-Dispositionattachment; filename="report-2026-11.pdf"save as a file with this name
Content-Length482113progress bar; omit when streaming
Cache-Controlprivate, no-storeno shared or disk caching of private data
Accept-Rangesbytesclient may request parts (resume)

2Writing the Endpoint

In this version the report is generated to a file first, which is common for PDF libraries and lets us know the size. We validate the month, check access, and return the file as a Resource.

Java
@GetMapping("/reports/{month}/pdf")
ResponseEntity<Resource> monthlyReport(@PathVariable String month, Principal user) throws IOException {
YearMonth ym = YearMonth.parse(month); // "2026-11"; anything else -> 400 via handler
Report report = reports.find(user.getName(), ym) // only this user's report
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
Path file = reportFiles.generateIfMissing(report); // our path, never from the request
ContentDisposition cd = ContentDisposition.attachment()
.filename("report-" + ym + ".pdf") // report-2026-11.pdf
.build();
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.contentLength(Files.size(file)) // 482113: browser shows progress
.header(HttpHeaders.CONTENT_DISPOSITION, cd.toString())
.cacheControl(CacheControl.noStore())
.body(new FileSystemResource(file)); // streamed from disk in chunks
}
// Content-Disposition: attachment; filename="report-2026-11.pdf"

Notice that FileSystemResource does not read the file into memory. Spring's ResourceHttpMessageConverter copies it to the response in small buffers, so a 200 MB report costs the same heap as a 200 KB one. ContentDisposition builds the header correctly, quoting the filename, which is safer than concatenating strings by hand.

3Avoiding a Fully Buffered File

The version to avoid is the one that generates the whole PDF into a ByteArrayOutputStream and returns its byte[]. For a 50 MB report and 20 concurrent downloads, that is 1 GB of heap, plus copies the array may need while growing. The alternatives depend on where the content comes from.

If the file is on disk, FileSystemResource is ideal. If it lives in object storage, we can wrap the storage client's InputStream in an InputStreamResource, which Spring copies to the response in chunks; we set Content-Length from the object's metadata when we have it. If the PDF is generated on the fly and the library can write to an OutputStream, StreamingResponseBody lets it write directly to the response, and in that case we omit Content-Length, because we do not know it in advance, and the server uses chunked transfer encoding.

Java
// generated on the fly, written straight to the response
@GetMapping("/reports/{month}/live.pdf")
ResponseEntity<StreamingResponseBody> live(@PathVariable String month, Principal user) {
Report report = authorisedReport(user, YearMonth.parse(month));
StreamingResponseBody body = out -> pdfRenderer.render(report, out); // library writes as it goes
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.header(HttpHeaders.CONTENT_DISPOSITION,
ContentDisposition.attachment().filename("report-" + month + ".pdf").build().toString())
.body(body); // no Content-Length
}

But there is a catch with direct streaming. If rendering fails halfway, the status 200 has already been sent and the user gets a broken file. For reports that take a long time or may fail, generating to a temporary file first and then serving it is more robust, and gives us Content-Length and Range support for free.

4Filenames With Non-ASCII Characters

The classic filename parameter only safely carries ASCII. If the report has a German name such as Bericht-Maerz-2026.pdf written with the character U+00E4 instead of ae, older behaviour varied by browser and produced garbled names. RFC 6266 together with RFC 5987 defines filename*, which carries the name percent-encoded with an explicit charset. Spring's ContentDisposition produces it when we pass a charset.

Java
ContentDisposition cd = ContentDisposition.attachment()
.filename("Bericht-März-2026.pdf", StandardCharsets.UTF_8)
.build();
// attachment; filename*=UTF-8''Bericht-M%C3%A4rz-2026.pdf

Modern browsers use filename* when present. Spring's exact output, for example whether it also includes an ASCII fallback filename, depends on the version, so check your version if old clients matter. The name itself should come from our data, not from the request, and we strip characters such as quotes, slashes and line breaks before using it.

5Authorisation and Path Traversal

Every download endpoint is an access-control decision. Being logged in is not enough; we check that this user may see this specific report. The example does it by looking the report up by the user and the month, so another user's report simply does not exist for them, and returning 404 instead of 403 avoids confirming that it exists.

We also never build file paths from user input. An endpoint like /files?name=../../etc/passwd that does baseDir.resolve(name) is the textbook path traversal bug. In our endpoint, the request only provides a month, which YearMonth.parse validates strictly, and the path comes from our own record. If a path must include user input, we resolve it against a base directory, normalise it and verify that the result still starts with the base directory before opening anything.

6Follow-up questions

How does Spring handle HTTP Range requests for resources?

When a controller returns a Resource in a ResponseEntity with status 200 and the request has a Range header, such as bytes=0-1048575, Spring MVC serves only that region: it responds 206 Partial Content with a Content-Range header, using ResourceRegion internally, and it sends multipart/byteranges for several ranges. This works for resources it can read at an offset, such as FileSystemResource. An InputStreamResource can only be read once from the start, so ranges are not applied to it; check your version for the exact behaviour. Range support lets browsers resume interrupted downloads and lets PDF viewers fetch pages on demand.

Should I use attachment or inline for a PDF?

Use attachment when the user expects to save the file, and inline when we want the browser's PDF viewer to open it in a tab. Inline is safe for PDFs we generate ourselves; for files uploaded by users, attachment from a separate domain is the safer default, because inline rendering of untrusted content can be abused.

Why not just return byte[] for small reports?

For reports that are always small, a few hundred kilobytes, byte[] is acceptable and simple. The risk is that reports grow over time, with more rows, images and months, and the endpoint's memory use grows with them. Using a Resource or a stream from the start costs no more code and removes the risk.

7Conclusion

In this answer, we wrote a Spring MVC endpoint that returns a generated PDF as a download named report-2026-11.pdf. We returned ResponseEntity<Resource> with application/pdf, a Content-Disposition built with ContentDisposition.attachment().filename(..), and Content-Length when the size is known; for large or live content we streamed with FileSystemResource, InputStreamResource or StreamingResponseBody instead of a byte[]. We encoded non-ASCII names with filename* by passing a charset, saw that FileSystemResource also supports Range requests, and checked authorisation for the specific report while keeping user input out of file paths.

What to say in the interviewAbout 90 seconds aloud

Open with

I would return ResponseEntity<Resource>. The method validates the month with YearMonth.parse, looks up the report for the current user, which is the authorisation check for this specific file, and gets the file path from our own record, never from the request, so there is no path traversal.

Then, if they want more

Then I build the response: content type application/pdf, a Content-Disposition header from ContentDisposition.attachment().filename("report-2026-11.pdf").build(), so the browser saves it with that name, Content-Length from Files.size so the browser can show progress, and Cache-Control no-store because it is private data.

The body is a FileSystemResource, which Spring copies to the response in small buffers, so memory stays flat no matter how big the file is. I would avoid generating the PDF into a byte array, because with large reports and concurrent downloads that fills the heap.

If the file is in object storage, I would wrap its stream in an InputStreamResource, and if the library can render directly to an OutputStream I can use StreamingResponseBody and omit Content-Length; but generating to a temp file first is more robust, because a failure halfway through a stream leaves a broken download.

For non-ASCII names, I pass a charset to filename so ContentDisposition writes filename* with UTF-8 percent encoding. And a bonus of FileSystemResource is that Spring MVC handles Range requests, returning 206 Partial Content, so downloads can resume.

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.
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 Spring MVC endpoint that returns a generated PDF report as a download named...": https://scrivio-interview-library.netlify.app/spring-boot/web-other/c82b724b60/