Roufid

Angular download file with Spring Boot

Angular

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 :

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.

Angular download service

That’s it.


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

References