I am using REST jersey on server side and AngularJS on client side.
My requirement is to download the zip file requested by client for specific date range.
Server side code: //Time being I have hardcoded one zip file for testing
@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){
StreamingOutput stream = new StreamingOutput(){
@Override
public void write(OutputStream arg0) {
// TODO Auto-generated method stub
BufferedOutputStream bus = new BufferedOutputStream(arg0);
try {
File file = new File("C:\\ProgramData\\ABC\\Logfiles\\UI.zip");
FileInputStream fizip = new FileInputStream(file);
byte[] buffer2 = IOUtils.toByteArray(fizip);
bus.write(buffer2);
bus.flush();
bus.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
return Response.status(Response.Status.OK).entity(stream).header("Content-Disposition","attachment; filename=\"log.zip\"").build();
}
Client side code:
$http({
url : urlBase + endPoint,
method: "POST",
data: formData, //this is your json data string
headers : {
'Content-Type' : "application/json",
'Authorization' : authCode,
},
responseType: 'arraybuffer'
}).success(function(response, status, headers, config) {
var blob = new Blob([response], { type: "application/zip" });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}).error(function (data, status, headers, config) {
//upload failed
});
File get downloaded in local but it is always corrupted and displays like below. Please help me on how to download file properly.
Below code may help you for downloading any type of file. change contentType
$scope.downloadFile = function(){
$http({
method : 'GET',
url : $scope.BASEURL + 'file-download?fileType='+$scope.selectedFile,
responseType: 'arraybuffer',
headers : {
'Content-Type' : 'application/json'
}
}).success(function(data, status, headers, config) {
// TODO when WS success
var file = new Blob([ data ], {
type : 'application/json'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = $scope.selectedFile+'.json';
document.body.appendChild(a);
a.click();
}).error(function(data, status, headers, config) {
});
}
url : $scope.BASEURL + 'file-download?fileType='+$scope.selectedFile
here you need to change url to your webservice url
Check this service, here you need to rturn the file as byte[]. change contentType
@RequestMapping(value = "/file-download", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody HttpEntity<byte[]> download(@RequestParam("fileType") String fileType, HttpServletRequest request, HttpServletResponse response){
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
HttpHeaders header = null;
byte[] document = null;
try {
JsonEditorBo jeBo = new JsonEditorBo();
String uploadsDir = "/download/";
String realPathtoUploads = request.getSession().getServletContext().getRealPath(uploadsDir);
if (!new File(realPathtoUploads).exists()) {
new File(realPathtoUploads).mkdir();
}
String downloadPath = jeBo.dowloadedFilePath(realPathtoUploads, fileType);
File file = new File(downloadPath);
document = FileCopyUtils.copyToByteArray(file);
header = new HttpHeaders();
header.setContentType(new MediaType("application", "json"));
header.set("Content-Disposition", "inline; filename=" + file.getName());
header.setContentLength(document.length);
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
e.printStackTrace();
}
return new HttpEntity<byte[]>(document, header);
}
CHANGES NEED please replace below code and check whether it is working or not
java.nio.file.Path path = Paths.get("C:\\ProgramData\\ABC\\Logfiles\\UI.zip");\
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
HTML
<html ng-app="ReviwerApp">
<div ng-controller="downloadCtrl">
<button ng-click="downloadzippedPdfs()" class="btn btn-danger">Download</button>
</div>
</html>
JavaScript
'use strict';
angular.module('downloads', []);
//Routers
myApp.config(function($stateProvider) {
$stateProvider.state('downloads', {
url: '/downloads',
templateUrl: 'partials/downloads/downloads.html',
data:{
auth:true
}
});
});
//Factories
myApp.factory('downloadServices', ['$http', function($http) {
var factoryDefinitions = {
getdownloadcontent: function() {
return $http.get('/smartcompare/rest/download/zip/2017-06-30', {
headers: {'Authorization': 'Basic xyz12345'},
responseType: 'arraybuffer'
}).then(function(response) { return response; });
},
}
return factoryDefinitions;
}
]);
//Controllers
myApp.controller('downloadCtrl', ['$scope', 'downloadServices' ,
function($scope, downloadServices ) {
var fileName = "comressedpdfreports.zip";
var a = document.createElement("a");
document.body.appendChild(a);
downloadServices.getdownloadcontent().then(function(response){
$scope.downloadzippedPdfs = function () {
var file = new Blob([response.data], {type: 'application/zip'});
var fileURL = URL.createObjectURL(file);
a.href = fileURL;
a.download = fileName;
a.click();
};
});
}]);
Java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import sun.misc.BASE64Decoder;
@Path("/download")
public class FileDownloadService {
@Path("/zip/{date}")
@GET
public Response downloadzipFile( @HeaderParam("authorization") String authString, @PathParam("date") String date)
{
{
StreamingOutput fileStream = new StreamingOutput()
{
@Override
public void write(java.io.OutputStream output) throws IOException, WebApplicationException
{
try
{
java.nio.file.Path path = Paths.get( "DailyReports"+File.separator+date+".zip");
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
}
catch (Exception e)
{
throw new WebApplicationException("File Not Found !!");
}
}
};
return Response
.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = "+date+".zip")
.build();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.