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…

Prerequisites

Knowledge of Spring REST API
Eclipse
JDK 1.8
Gradle
Spring Boot dependencies

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 = '1.5.9.RELEASE'
	}
    repositories {
		mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
jar {
    baseName = 'SpringBootFileUpload'
    version = '0.0.1-SNAPSHOT'
    manifest {
        attributes("Main-Class": "com.jeejava.main.Application")
    }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
	mavenLocal()
    mavenCentral()
}
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
}

 Creating application.properties file

We are creating below application.properties 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.

server.port=9999

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.jeejava.entity;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonFormat;

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@Column(name = "EMPLOYEE_ID")
	private String empId;

	@Column(name = "EMPLOYEE_FIRST_NAME")
	private String empFirstName;

	@Column(name = "EMPLOYEE_LAST_NAME")
	private String empLastName;
	
	//getters and setters
}

Creating Spring Data JPA Repository class

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.jeejava.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.jeejava.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.jeejava.service;

@Service
public class EmployeeService {
	@Resource
	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.jeejava.controller;

@RestController
public class FileUploadRestController {
	@Autowired
	private EmployeeService employeeService;
	@GetMapping("/download")
	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.setContentLength(isr.length);
		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.jeejava.application;

@SpringBootApplication(scanBasePackages = "com.jeejava")
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, 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.

[
	{"empId":"1003349","empFirstName":"Liton","empLastName":"Sarkar"},
	{"empId":"1003350","empFirstName":"Debabrata","empLastName":"Poddar"},
	{"empId":"1003351","empFirstName":"Abhisekh","empLastName":"Paul"},
	{"empId":"1003352","empFirstName":"Sumit","empLastName":"Ghosh"},
	{"empId":"1003353","empFirstName":"Manoj","empLastName":"Kumar"},
	{"empId":"1003354","empFirstName":"Sreeja","empLastName":"Chowdhury"}
]

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

That’s all. Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

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