从REST Web服务+ AngularJS下载zip文件

时间:2016-11-15 09:23:51

标签: javascript java angularjs rest jersey

我在服务器端使用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
});

文件在本地下载但它总是损坏并显示如下。 请帮我说明如何正确下载文件。 enter image description here

2 个答案:

答案 0 :(得分:0)

下面的代码可以帮助您下​​载任何类型的文件。更改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 +'文件下载?fileType ='+ $ scope.selectedFile

此处您需要将网址更改为您的网络服务网址

检查此服务,在这里您需要将文件调整为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();

答案 1 :(得分:0)

<强> 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();


    }