Introduction

In this post we will see how to download file using Angular and Spring Boot. There are situations where you need to download file from server or you need to generate report from database and download it. This example may help you in that situation. Here we will fetch records from database and download in a JSON format. As a server side technology we will use Spring Boot 2.1.5 and in client side we will use Angular 7.

You may also like to read Download file using React and Spring Boot.

Prerequisites

Eclipse Neon, Java 1.8, Gradle 5.4.1

Download file from server using Angular

Example with Source Code

Creating Project

Create gradle based project in Eclipse, the project structure may look similar to the below image:

download file using angualr and spring boot

Updating Build Script

Update the default generated content in build script. You need to include the required dependencies for Spring Boot, JPA and H2 in-memory database. We are using in-memory database to do a quick PoC. You can use any database as per your project requirements.

buildscript {
	ext {
		springBootVersion = '2.1.5.RELEASE'
	}
    repositories {
    	mavenLocal()
    	mavenCentral()
    }
    dependencies {
    	classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
	mavenLocal()
    mavenCentral()
}
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
	compile("org.springframework.boot:spring-boot-starter-data-jpa:${springBootVersion}")
	runtime("com.h2database:h2:1.4.196")
}

Creating Properties File

Create a property file called application.yml under classpath directory src/main/resources with the below content to enable h2 console and log the SQL statement used for database operations in pretty format in the console.

spring:
   jpa:
      show-sql: true
   h2:
      console:
         enabled: true

Creating Entity Class

We need an entity class to map our Java attribute to database table’s column.

We will not create any SQL script for creating table in h2 database but Spring Boot will automatically create the table for below entity class.

If we do not specify the column name for the corresponding Java attribute or field then the same attribute name will be used to create column in the database table.

You don’t need to define any datasource when you are using in-memory embedded database h2.

package com.roytuts.spring.file.download.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	private String name;
	@Column(name = "email_address")
	private String email;
	public Employee() {
	}
	public Employee(Integer id, String name, String email) {
		this.id = id;
		this.name = name;
		this.email = email;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

Inserting Data into Table

Spring Boot will create table from entity class but we need to insert some data into the table.

So we will create a SQL script called data.sql under classpath directory src/main/resources as shown below:

insert into employee(name,email_address)
values('Soumitra','[email protected]');
insert into employee(name,email_address)
values('Liton','[email protected]');
insert into employee(name,email_address)
values('Suman','[email protected]');
insert into employee(name,email_address)
values('Debabrata','[email protected]');

Creating JPA Repository

Spring has excellent API called Spring Data JPA Repository that gives us many benefits out of the box. You just need to write methods by extending JpaRepository interface for performing basic CRUD operations. Then Spring will generate appropriate queries for your methods.

package com.roytuts.spring.file.download.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.roytuts.spring.file.download.entity.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
}

Creating VO Class

It’s a good idea to create DTO or VO class as a response object rather than entity class.

package com.roytuts.spring.file.download.vo;
public class EmployeeVo {
	private Integer id;
	private String name;
	private String email;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

Creating Service Class

Service class is always used to process your business for the application.

package com.roytuts.spring.file.download.service;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.roytuts.spring.file.download.entity.Employee;
import com.roytuts.spring.file.download.repository.EmployeeRepository;
import com.roytuts.spring.file.download.vo.EmployeeVo;
@Service
public class EmployeeService {
	@Autowired
	private EmployeeRepository employeeRepository;
	public List<EmployeeVo> getEmployeeList() {
		List<Employee> list = employeeRepository.findAll();
		return list.stream().map(emp -> {
			EmployeeVo vo = new EmployeeVo();
			vo.setId(emp.getId());
			vo.setName(emp.getName());
			vo.setEmail(emp.getEmail());
			return vo;
		}).collect(Collectors.toList());
	}
}

Creating REST Controller

The Spring REST Controller class is responsible for handling request/response for the end users or clients.

Here in the below Spring REST controller class, we fetch the data from database and convert into JSON data to send to the client as byte array.

We allow request and response for the origin http://localhost:4200 using @CrossOrigin(origins = “http://localhost:4200”). If you do not allow cross-origin request/response for the mentioned URL then you won’t be able to download file. You can also put * to allow all origins.

package com.roytuts.spring.file.download.rest.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.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.roytuts.spring.file.download.service.EmployeeService;
import com.roytuts.spring.file.download.vo.EmployeeVo;
@RestController
@CrossOrigin(origins = "http://localhost:4200")
public class EmployeeRestController {
	@Autowired
	private EmployeeService employeeService;
	@GetMapping("/employees/download")
	public ResponseEntity<byte[]> downloadFile() throws Exception {
		List<EmployeeVo> employees = employeeService.getEmployeeList();
		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 Main Class

Create below main class to deploy the application into embedded Tomcat server.

We need to let Spring container know where are our entity class and repository interface. You can also use a separate configuration class to enable such things.

package com.roytuts.spring.file.download;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EntityScan("com.roytuts.spring.file.download.entity")
@EnableJpaRepositories("com.roytuts.spring.file.download.repository")
@SpringBootApplication(scanBasePackages = "com.roytuts.spring.file.download")
public class SpringRestFileDownload {
	public static void main(String[] args) {
		SpringApplication.run(SpringRestFileDownload.class, args);
	}
}

Testing the Application

Run the main class to deploy the application into Tomcat server.

Also run the Angular application to open in browser.

Once your application opens at URL http://localhost:4200 in the browser and the page may look similar to the below image:

download file using angular and spring boot

When you click on link or button for downloading file you will see below page with file save option:

download file using angular and spring boot

Source Code

You can download source code.

You may also like to read Download file using React and Spring Boot.

Thanks for reading.

Tags:

Leave a Reply

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