How to download a file in Angular2
Tech-Today

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 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.




- Display A Byte[] Image From A Rest Web Service
This tutorial will not delve into angular nor will we discuss what a directive is. We will not try to explain what a rest web service is. Instead we will provide a demonstration via actual code, how we can consume a rest service from angular that returns...

- How To Download A File In Soap Api
First we define the interface like this: @WebMethod ActionStatus downloadFile(@WebParam(name = "file") String file); Implementation: public ActionStatus downloadFile(String filePath) { MessageContext mc = webServiceContext.getMessageContext(); // see...

- How To Download A File Using Rest Api
Normally I create an interface when defining a REST api, this is useful when testing using Arquillian. To define a download file api we must define the method below in the interface. @GET @Path("/downloadFile") ActionStatus downloadFile(@QueryParam("file")...

- How To Read And Write Csv Using Jackson Library
The sample code below demonstrates how we can read a csv file into an array of objects. Also it writes an array of objects into csv. To use don't forget to include in your pom.xml <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId>...

- How To Solve Multiple Active Datareader Session In Mvc3 C#
This problem commonly happens when you try to execute a query with a return type of IEnumerable then execute a second query with the result. Example, we have a table Animes: public IEnumerable GetAnimes() { return context.Animes; } //on the second part...



Tech-Today








.