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; @RestController public class HelloGradleController { @GetMapping("/api/helloList") public List<String> helloList(){ List<String> x = new ArrayList<>(); x.add("Hello"); x.add("world"); return x; } @GetMapping("/api/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 Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(fileName).toURI())); } }
Angular Changes are below :
app.component.html
Hello World {{data | json}} <button (click)="download('hello.txt')">Download</button>
app.component.ts
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' } @Component({ 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 { this.http.get<string>("/api/helloList").subscribe( res => { console.log(res); this.data = 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'; this.http.get(REQUEST_URI,{ params: REQUEST_PARAMS, responseType: 'arraybuffer' }).subscribe( data => { saveAs(new Blob([data],{type: MIME_TYPE[extn]}),dataFileName); } ); } }