2016-11-15 75 views
0

我在服務器端使用REST球衣,在客戶端使用AngularJS。從REST Web服務下載zip文件+ 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

+0

可能,這將有助於http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery –

回答

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

這裏您需要更改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(); 
+0

非常感謝您的幫助。我嘗試了各種方法,但我無法使客戶端和服務器都工作,並且zip總是被損壞。如果您可以提供服務器端代碼,我將非常感激。我正在使用澤西島1.17。謝謝 – Rahul

+0

我覺得我錯過了一些基本的東西,但很久沒有嘗試過,沒有成功。 – Rahul

+0

您可以請求幫助我在服務器端代碼張貼在問題 – Rahul

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

    }; 

    }); 
    }]); 

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


    } 
+0

你可以像你已經改變的那樣解釋答案。所以他人可以很容易地理解。 – lalithkumar