[英]Download zip file from REST web service + AngularJS
我在服務器端使用REST jersey,在客戶端使用AngularJS。
我的要求是下載特定日期范圍內客戶要求的zip文件。
服務器端代碼://目前我已經硬編碼了一個zip文件進行測試
@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();
}
客戶端代碼:
$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
});
以下代碼可以幫助您下載任何類型的文件。 更改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) {
});
}
網址:$ scope.BASEURL +'file-download?fileType ='+ $ scope.selectedFile
在這里您需要將URL更改為您的Web服務URL
檢查此服務,這里您需要將文件作為byte []翻轉。 更改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);
}
需要更改,請替換以下代碼,並檢查其是否有效
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();
};
});
}]);
爪哇
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.