File download example using Spring REST Controller will show you how to download a file from any client (browser or any client) and Spring REST service is used as a server side technology for downloading the file. The file may be any type, i.e., such as excel, text, word, pdf etc. Here we will create Spring Boot application as it reduces our most of the efforts in project configurations.

We have seen how to download a file using REST web service using Jersey API in my other tutorial but here we will see how to download a file using Spring REST Controller.

You may also like to read my previous tutorial on file upload using Spring REST Controller.

For various reasons, such as, reporting or any other purpose you may need to download file and in our today’s application we are using mostly REST services to make the application loosely coupled, it is sometimes required to download the file using REST service.

Recommended reading: Junit Testing of File Upload and Download in Spring REST Controllers

Let’s move on to file download example using Spring REST Controller…


Knowledge of Spring REST API
JDK 1.8
Gradle 4.10.2
Spring Boot 2.1.3

Example with Source Code

Setting up project

As a prerequisite we have to first setup the project environment so that we would be able to write the required code for downloading file into server and save the file anywhere on a physical location in your system. Create below build.gradle script to add the required project dependencies. We have also specified the JDK version we will be using for our application. File download example using Spring REST Controller does not many dependencies and you need to add only spring boot started web for downloading a file.

buildscript {
	ext {
		springBootVersion = '2.1.3.RELEASE'
    repositories {
    dependencies {
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
jar {
    baseName = 'SpringBootFileDownload'
    version = '0.0.1-SNAPSHOT'
    manifest {
        attributes("Main-Class": "com.roytuts.main.Application")
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
dependencies {


We are creating below file under classpath directory src/main/resources to override default port 8080 of Tomcat server as we don’t want to start our server run on default port 8080. So we want our server to be started on 9999 port. It avoids conflicts if any tomcat instance already running on port 8080. You can also run the tomcat server on a random port.


Creating Entity Class

Create below entity class that maps to database table. Our entity class has only three fields employee id, employee first name and employee last name. We are creating entity class because we want to create a file from our database record and finally download the file using Spring REST service. Here we will build a JSON file from database employee table and download that JSON file. You can build any type of file, such as excel file, csv file etc. to fulfil your project’s requirement.

package com.roytuts.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;
	@Column(name = "EMPLOYEE_ID")
	private String empId;
	@Column(name = "EMPLOYEE_FIRST_NAME")
	private String empFirstName;
	@Column(name = "EMPLOYEE_LAST_NAME")
	private String empLastName;
	public String getEmpId() {
		return empId;
	public void setEmpId(String empId) {
		this.empId = empId;
	public String getEmpFirstName() {
		return empFirstName;
	public void setEmpFirstName(String empFirstName) {
		this.empFirstName = empFirstName;
	public String getEmpLastName() {
		return empLastName;
	public void setEmpLastName(String empLastName) {
		this.empLastName = empLastName;

Creating Spring Data JPA Repository

Here in the file download example using Spring REST Controller, we are using Spring Data JPA in order to query the database and fetch data from database table. So create below Spring Data JPA Repository which provides most of our built-in methods to query database for fetching data.

package com.roytuts.repository;
import com.roytuts.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {

Creating Spring Service Class

Create below service class which will fetch data from Spring Data JPA Repository and send to Spring REST Controller that will generate the file for download. We fetch all employees from the database using the below service layer code. We annotate the service layer class using @Service. We create service layer class to process our business logic to avoid any tight coupling between the layers.

package com.roytuts.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.roytuts.entity.Employee;
import com.roytuts.repository.EmployeeRepository;
public class EmployeeService {
	private EmployeeRepository employeeRepository;
	public List<Employee> getEmployees() {
		return employeeRepository.findAll();

Creating Spring REST Controller

This is where we write code for file download example using Spring REST Controller. The below Spring REST Controller class to receive the downloaded file from client. We have the http method GET request and the file can be downloaded from browser or any REST client or UI. We use the data type as array of byte stream in the response to download the file. File may be downloaded from a selected location using the server side code or you may generated a report file from database and download the report file using the Spring REST Controller. Notice how we attach the file in the http header response so that file will be forced to download and give a pop-up for saving it. You must specify few things, such as, content length, content type, attachment with file name in order to download the file forcefully.

package com.roytuts.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.roytuts.entity.Employee;
import com.roytuts.service.EmployeeService;
public class FileDownloadRestController {
	private EmployeeService employeeService;
	public ResponseEntity<byte[]> downloadErrorData() throws Exception {
		List<Employee> employees = employeeService.getEmployees();
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(employees);
		byte[] isr = json.getBytes();
		String fileName = "employees.json";
		HttpHeaders respHeaders = new HttpHeaders();
		respHeaders.setContentType(new MediaType("text", "json"));
		respHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
		respHeaders.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
		return new ResponseEntity<byte[]>(isr, respHeaders, HttpStatus.OK);

Creating Spring Boot Main Class

Now major coding part is done and it’s time to deploy the application into embedded tomcat server. Create below Spring Boot main class to deploy the application into Tomcat server.

package com.roytuts.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.roytuts")
public class Application {
	public static void main(String[] args) {, args);

Testing the application

Now it’s time to test the application for file download example using Spring REST Controller. You may also like to read my previous tutorial on file upload using Spring REST Controller.

When you hit the URL http://localhost:9999/download from browser or REST client then you would be able to receive the below JSON records in a file assuming your database employee table has the similar records.


Recommended reading: Junit Testing of File Upload and Download in Spring REST Controllers

Source Code

That’s all. Thanks for reading.


Leave a Reply

Your email address will not be published. Required fields are marked *