This tutorial shows a step by step solution to Angular download file Spring Boot backend. We will cover  the download of files located in system and others in classpath.

Server side

This section covers the Spring Boot server implementation

Spring Boot Controller

Our application exposes two endpoints to download CSV files. The first controller downloads files that are located in system and the second from class path.  Below the implementation :

  • @RestController is used to make the Java Class handle HTTP requests. @RestController is a shortcut of the combination of @Controller along with @ResponseBody.
  •  The controller handles two GET HTTP requests and produces a  text/csv; charset=utf-8 media type and returns response body of type Resource.
  • The name of the file to download is given as a @PathVariable

The controller is as simple as you see. Let’s see now the  FileService.

Spring Component FileService

We extracted the logic of retrieving the files in a Spring Component FileService. Below it’s content :

Retrieving files is quite simple with Spring. For a file located in system, FileSystemResource is used to wich we pass the absolute path to file. And for a file located in class path, ClassPathResource is used with the absolute path within the class path.

A Content-Disposition header is added to the HTTP response with attachment as value in order to make the file downloadable and savable locally.

That’s it for server side. Let’s see now the front end implementation.

Client side with Angular

I used Angular CLI to create the application. I also use  the file-saver NPM library. To install it :  npm i --save file-saver

Angular component

For this tutorial, a simple component is created with two filename inputs and two corresponding submit buttons. The first to download file located in file system and the second in class path.

  • app.component.html
  • app.component.ts

Angular download service

That’s it.

The tutorial source code is available on Github. Download the source