Spring Boot File Download via Angular7 PART 01

Create a Simple Spring Boot App.

As a pre-requisite, we need to implement a service with file download feature.

Video guide of the spring-boot process



 

So I composed the below class, which is a complete spring boot application, with file download functionality at its simplest form.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package snmaddula.quicktrick.ng;

import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;

import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class FileDownloadApp {

@GetMapping("/download")
public void downloadFile(String fileName, HttpServletResponse res) throws Exception {
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.getOutputStream().write(contentOf(fileName));
}

private byte[] contentOf(String fileName) throws Exception {
return readAllBytes(get(getClass().getClassLoader().getResource(fileName).toURI()));
}

public static void main(String[] args) {
SpringApplication.run(FileDownloadApp.class, args);
}
}

The only dependency that is needed for this boot application is spring-boot-starter-web, add it to your pom.xml

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

For testing purpose, we need some files to be available for download.
So place some files in your application classpath under src/main/resources like below: (.xls, .xlsx, .pdf, etc)

With this we are done with the server side / spring boot side of the application. Now, let us write the Angular side implementation.