2017-06-13 65 views
0

大家好,我正在使用angularjs java和rest来实现一个报告。根据选择的UI字段,会调用Java Layer,并从java中调用一些数据库调用,并将返回的输入流以csv文件形式下载。 有一个问题发生,如果我做同样的点击相同的网址浏览器,即时通过angularjs比我能够下载文件,但如果通过使用UI即时通讯使得请求比没有下载选项和数据返回作为http响应角度的流。正在下载一个Csv文件来自angularjs Jax-Rs和java

Java代码:

enter code here 
    @Path("/files") 
    public class DownloadCsvFile { 

    @GET 
    @Path("/csv") 
    @Produces({MediaType.APPLICATION_OCTET_STREAM}) 
    public Response getFile() { 
    StreamingOutput outp = new StreamingOutput() { 
     @Override 
     public void write(OutputStream out) throws IOException, 
     WebApplicationException { 
     String url ="http://someurl? 
     indent=on&q=RCE_POST:2016&sort=id%20asc 
     &rows=100000&start=0&wt=csv"; 
     final InputStreamReader is = new InputStreamReader(
        ((HttpURLConnection) (new URL(url)).openConnection()) 
        .getInputStream(), 
        Charset.forName("UTF-8")); 

     IOUtils.copy(is, out); 
     } 
    }; 

    ResponseBuilder response = Response.ok(outp); 
    response.header("Content-Disposition", "attachment; 
    filename=\"testFile_file.csv\""); 
    return response.build(); 

     } } 

AngularJs控制器代码:

enter code here 
     var app = angular.module('myApp', ['ngProgress']); 
     app.controller('myCtrl', function($scope,$http,ngProgressFactory) { 
     // on submit the fun is called 
     $scope.LMALLPeriodReport =function() 
     { 
      return $http.get("http://localhost:8080/IsaveIdeas/rest/files/csv? 
      parameters="+parameter) 
      //parameter contain the selected field in UI 
      .then(function (response) { 
      var result = response.data; 
      alert("printing data"); 
     }); 
     }; 

从浏览器http://localhost:8080/IsaveIdeas/rest/files/csv相同的请求? parameters = {parameter}使我能够下载文件。

回答

0

您可以使用一滴在angularjs这样的代码:

.... 
.then(function (response) { 

var fileName = "yourFileName.csv"; 
var a = document.createElement("a"); 
document.body.appendChild(a); 
response.data = "\ufeff" + response.data; 
var file = new Blob([response.data], {encoding:"UTF-8",type:'application/csv;charset=UTF-8'}); 
var fileURL = URL.createObjectURL(file); 
a.href = fileURL; 
a.download = fileName; 
a.click(); 
}