Wednesday, 16 November 2016

Download binary file AngularJS + REST service

Download binary file using AngularJS + REST service

Many a times we need to download file via POST request, because the request contains extra parameters to pass and GET request is not suitable.   
download file from server example in angularjs
Download file from server example in AngularJS

Lets see example of downloading ZIP file via POST request. 

For downloading file in Angular2 look at this post: Download file in Angular2

Example demonstrates downloading binary file using Javascript and REST service


Once I have faced requirement of downloading binary zip file using AngularJS + REST service and thought of sharing the code, It may help to someone facing similar requirement.

Javascript client code


index.html
<!DOCTYPE html>
<html ng-app="webAdminApp">
 <head>
  <title>AngularJS + REST service Binary download Example</title>
     <!-- JQUERY -->
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>     
     
     <!-- ANGULAR -->
     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
  
     <!-- CUSTOM -->
     <script src="logController.js"></script>
 </head>
 <body ng-controller="logController">
   
   <form name="logForm" novalidate>
  <input type="text" name="parameter1" ng-model="parameter1">
  <input type="text" name="parameter2" ng-model="parameter2">
  <input type="text" name="parameter3" ng-model="parameter3">
  <input type="button" ng-click="downloadLogs()" value="Download">
 </form> 
  
 </body>
</html> 

logController.js
var app = angular.module('webAdminApp',[]);
app.controller("logController", function($scope) {
 
 $scope.downloadLogs = function (){
  var pathString = window.location.protocol + "//" + window.location.host + window.location.pathname;
  var url = pathString+'restunsecure/LogService/LogRange';
  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.responseType = "arraybuffer";
  xhr.onload = function () {
      if (this.status === 200) {
          var blob = new Blob([xhr.response], {type: "application/zip"});       
          var a = document.createElement('a');
             a.href = URL.createObjectURL(blob);
             a.download = "filename.zip";
             a.click();
      }
  };
  xhr.send(JSON.stringify(
   { "parameter1": $scope.parameter1, 
    "parameter2": $scope.parameter2, 
    "parameter3": $scope.parameter3
   })
  ); 
 };
 
});

Java REST service.


LogsService.java
package com.javabypatel.services;

import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.io.IOUtils;

import com.javabypatel.services.dto.LogFolders;

@Path("/LogService")
public class LogsService {

 @POST
 @Path("/LogRange")
 @Produces({MediaType.APPLICATION_OCTET_STREAM} )
 @Consumes({ MediaType.APPLICATION_JSON} )
 public Response getLogsBetween(
   @HeaderParam(HttpHeaders.AUTHORIZATION) String authorization, 
   @Context HttpServletRequest request, @Context HttpServletResponse response,
   LogFolders folders){
  
  System.out.println("Testing Download with parameters :"+
    folders.getProperty1() + " - " + folders.getProperty2() + " - " + folders.getProperty3());

  byte[] buffer2 = null;
  try {
   File file = new File("PathToZipFile\\Sample.zip");
   FileInputStream fis = new FileInputStream(file);
   buffer2 = IOUtils.toByteArray(fis);
   fis.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return Response.ok(buffer2)
    .header("Content-Length", buffer2.length)
    .header("Content-Disposition","attachment; filename=TestFile.zip").build();
 }
}



LogFolders.java
package com.javabypatel.services.dto;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class LogFolders{
 
 @JsonProperty("property1")
 public String property1;
 
 @JsonProperty("property2")
 public String property2;
 
 @JsonProperty("property3")
 public String property3;

 public String getProperty1() {
  return property1;
 }
 public void setProperty1(String property1) {
  this.property1 = property1;
 }
 public String getProperty2() {
  return property2;
 }
 public void setProperty2(String property2) {
  this.property2 = property2;
 }
 public String getProperty3() {
  return property3;
 }
 public void setProperty3(String property3) {
  this.property3 = property3;
 }
}


Running the Application


Open URL as "http://localhost:8080/ProjectName/"
Fill all 3 textbox with data and enter Download button.

Request will go to Server with payload JSON containing all 3 parameters.
JSON will get mapped to LogFolders POJO and download Sample ZIP file.


You may also like to see


Implement Stack using One Queue


Find Largest and Smallest number in Array

Count zeros in a row wise and column wise sorted matrix

Find middle element of a linked list

Union and Intersection of Two Sorted Arrays

Merge two sorted arrays in Java

How is ambiguous overloaded method call resolved in java

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

No comments:

Post a Comment