Download a File using Angular and SpringBoot

We need to install node package called file save to run below demo :

npm i -s file-saver

Note : In below example we are downloading file from the resource folder but we can also make a file download by giving its path.

Spring Boot Changes are below :

package CsrfSpringDemo;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class HelloGradleController {

	public List<String> helloList(){
		List<String> x = new ArrayList<>();
		return x;
	public void downloadFile(String fileName, HttpServletResponse res) throws Exception {
		res.setHeader("Content-Disposition","attachment; filename="+fileName);
	private byte[] contentOf(String fileName) throws Exception{
		return Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(fileName).toURI()));

Angular Changes are below :


Hello World
{{data | json}}
<button (click)="download('hello.txt')">Download</button>


import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { saveAs } from 'file-saver';

const MIME_TYPE = {
  pdf: 'application/pdf',
  txt: 'application/text'

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit{
  title = 'CsrfDemo';
  data: string;
  constructor(private http: HttpClient){

  ngOnInit(): void {
      res => { console.log(res); = res; },
      err => { console.log(JSON.stringify(err)); },
      () => { console.log('Api Call completed'); }

  download(dataFileName) {
    const extn = dataFileName.substr(dataFileName.lastIndexOf('.')+1);
    const REQUEST_PARAMS = new HttpParams().set('fileName', dataFileName);
    const REQUEST_URI = '/api/download';
      params: REQUEST_PARAMS,
      responseType: 'arraybuffer'
      data => {
        saveAs(new Blob([data],{type: MIME_TYPE[extn]}),dataFileName);

Leave a Comment