In web applications, serving static files like PDFs is a common requirement, especially when dealing with documents, reports, or downloadable content. Micronaut, a modern JVM-based framework for building microservices and serverless applications, provides convenient features for handling file downloads from controllers. In this blog, we’ll explore how to serve PDF files from a Micronaut controller using practical code examples and step-by-step explanations.
Inside the controller method, retrieve the PDF file based on the provided name. Ensure that the file exists and is accessible. If the file is found, return an HTTP response with the file content and appropriate headers.
@Get("/final/{id}/download")
suspend fun invoiceDownload(id: String): MutableHttpResponse<File>? {
val file: File = // Fetch File
return HttpResponse.ok(file)
.contentType(MediaType.APPLICATION_PDF)
.header("Content-Disposition", "filename=${file.name}")
}
In this blog, we’ve explored how to serve PDF files from a Micronaut controller. By creating a dedicated controller method and handling file retrieval and HTTP responses appropriately, we can seamlessly serve PDF files to clients. This capability is invaluable for applications that need to provide downloadable documents or reports to users, enhancing the overall user experience and functionality of the application.