How to download a file in Angular2

There are 2 ways I use to download a file with Angular2 or greater. For this example, we will use a Java REST service. The first approach wo...


There are 2 ways I use to download a file with Angular2 or greater. For this example, we will use a Java REST service.

The first approach would be taking advantage of the HTTP download, where the Angular side will just call a URL that will initiate the download.

Here's the web service's code
// The download resource
@GET
@Path("/exportCSV")
Response exportCSV();

@Override
public Response exportCSV() throws IOException {
ResponseBuilder builder = Response.ok();
builder.entity(tallySheetApi.exportCSV(httpServletResponse));

return builder.build();
}

public void exportCSV(HttpServletResponse response) throws IOException {
// write result to csv file
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.setContentType("text/csv");
response.addHeader("Content-disposition", "attachment;filename=\"animes.csv\"");

writeToCSV(response.getOutputStream(), listValuesHere);

response.flushBuffer();
}

private void writeToCSV(ServletOutputStream servletOutputStream, List<Anime> animes) throws IOException {
Writer writer = new BufferedWriter(new OutputStreamWriter(servletOutputStream));

for (Anime anime : animes) {
writer.write(anime.getTitle());
writer.write(CSV_DELIMITER);
writer.write(anime.getReleaseDate());
writer.write(CSV_DELIMITER);
writer.write(anime.getRating());

writer.write(System.getProperty("line.separator"));
}

writer.close();
}

In the Angular part, we need to call the method below that will redirect to the url we defined above.
exportCSV() {
window.location.href = this.apiUrl + this.RESOURCE_URL + '/exportCSV';
}

The problem with this approach is that we cannot send security header in the request. To solve that issue we need to update both our api and the way we handle the response in Angular.
public class ByteDto {

private String fileContent;

public String getFileContent() {
return fileContent;
}

public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}

}

// The download resource
@GET
@Path("/exportCSV")
Response exportCSV();

@Override
public Response exportCSV() throws IOException {
ResponseBuilder builder = Response.ok();
builder.entity(tallySheetApi.exportCSV());

return builder.build();
}

public ByteDto exportCSV() throws IOException {
ByteArrayOutputStream baos = writeToCSV(listValuesHere);

ByteDto byteDto = new ByteDto();
byteDto.setFileContent(Base64.getEncoder().withoutPadding().encodeToString(baos.toByteArray()));

return byteDto;
}

private ByteArrayOutputStream writeToCSV(List<Anime> animes) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Writer writer = new BufferedWriter(new OutputStreamWriter(baos));

for (Anime anime : animes) {
writer.write(anime.getTitle());
writer.write(CSV_DELIMITER);
writer.write(anime.getReleaseDate());
writer.write(CSV_DELIMITER);
writer.write(anime.getRating());

writer.write(System.getProperty("line.separator"));
}

writer.close();

return baos;
}
In this approach, we save the byte array in a DTO instead of writing it in the outputStream. Note that we needed to encode the byte array as Base64, otherwise we will have a problem during deserialization. It also requires some additional work on the Angular side.
exportCSV() {
this.http.get<any>( this.apiUrl + this.RESOURCE_URL + '/exportCSV', { params: this.params } ).subscribe( data => {
console.log( 'downloaded data=' + data.fileContent )
var blob = new Blob( [atob( data.fileContent )], { type: 'text/csv' } )
let filename = 'animes.csv'

if ( window.navigator && window.navigator.msSaveOrOpenBlob ) {
window.navigator.msSaveOrOpenBlob( blob, filename )
} else {
var a = document.createElement( 'a' )
a.href = URL.createObjectURL( blob )
a.download = filename
document.body.appendChild( a )
a.click()
document.body.removeChild( a )
}
} )
}
In this version we needed to decode the byte array from the response and use the msSaveOrOpenBlob method from windows.navigator object. We also need to create a tag on the fly to invoke the download.

COMMENTS

mas template
Name

amazon,1,angular,8,bigdata,2,business,1,course-spring,27,courses,6,database,4,docker,3,java,50,kafka,1,keycloak,4,microservices,5,mysql,1,neworking,1,nosql,2,php,1,pinned,2,react,3,server management,7,shared drive,1,spring,7,synology,1,troubleshooting,2,web,1,wordpress,1,
ltr
item
toztech: How to download a file in Angular2
How to download a file in Angular2
https://1.bp.blogspot.com/-ii9WB_TJfOQ/XQoSWzDs02I/AAAAAAAAKf4/xlfLWQrgjdoy-wJYYeY9BiLIGs2ppSiigCEwYBhgL/s320/angular.png
https://1.bp.blogspot.com/-ii9WB_TJfOQ/XQoSWzDs02I/AAAAAAAAKf4/xlfLWQrgjdoy-wJYYeY9BiLIGs2ppSiigCEwYBhgL/s72-c/angular.png
toztech
https://toztech.blogspot.com/2018/06/how-to-download-file-in-angular2.html
https://toztech.blogspot.com/
https://toztech.blogspot.com/
https://toztech.blogspot.com/2018/06/how-to-download-file-in-angular2.html
true
2554149350007112447
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content