How To Download A File Inwards Angular2

There are ii ways I role to download a file alongside Angular2 or greater. For this example, nosotros volition role a Java REST service.

The starting fourth dimension approach would last taking payoff of the HTTP download, where the Angular side volition simply telephone phone a URL that volition initiate the download.

Here's the spider web service's code
 // The download resources @GET @Path("/exportCSV") Response exportCSV();  @Override world Response exportCSV() throws IOException {  ResponseBuilder builder = Response.ok();  builder.entity(tallySheetApi.exportCSV(httpServletResponse));   supply builder.build(); }  world 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(); }  mortal void writeToCSV(ServletOutputStream servletOutputStream, List<Anime> animes) throws IOException {  Writer author = novel 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, nosotros take to telephone phone the method below that volition redirect to the url nosotros defined above.
 exportCSV() {  window.location.href = this.apiUrl + this.RESOURCE_URL + '/exportCSV'; } 

The occupation alongside this approach is that nosotros cannot mail safety header inward the request. To solve that number nosotros take to update both our api in addition to the trend nosotros grip the reply inward Angular.
 world class ByteDto {   mortal String fileContent;   world String getFileContent() {   supply fileContent;  }   world void setFileContent(String fileContent) {   this.fileContent = fileContent;  }   }  // The download resources @GET @Path("/exportCSV") Response exportCSV();  @Override world Response exportCSV() throws IOException {  ResponseBuilder builder = Response.ok();  builder.entity(tallySheetApi.exportCSV());   supply builder.build(); }  world ByteDto exportCSV() throws IOException {  ByteArrayOutputStream baos = writeToCSV(listValuesHere);     ByteDto byteDto = novel ByteDto();  byteDto.setFileContent(Base64.getEncoder().withoutPadding().encodeToString(baos.toByteArray()));   supply byteDto; }  mortal ByteArrayOutputStream writeToCSV(List<Anime> animes) throws IOException {  ByteArrayOutputStream baos = novel ByteArrayOutputStream();  Writer author = novel 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();    supply baos; } 
In this approach, nosotros salve the byte array inward a DTO instead of writing it inward the outputStream. Note that nosotros needed to encode the byte array equally Base64, otherwise nosotros volition convey a occupation during deserialization. It besides requires unopen to additional come about the Angular side.
 exportCSV() {  this.http.get<any>( this.apiUrl + this.RESOURCE_URL + '/exportCSV', { params: this.params } ).subscribe( information => {   console.log( 'downloaded data=' + data.fileContent )   var blob = novel Blob( [atob( data.fileContent )], { type: 'text/csv' } )   allow 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 nosotros needed to decode the byte array from the reply in addition to role the msSaveOrOpenBlob method from windows.navigator object. We besides take to practice a tag on the wing to invoke the download.
Next
Previous
Click here for Comments

0 komentar:

Please comment if there are any that need to be asked.