下载Csv文件来自angularjs Jax-Rs和java

时间:2017-06-13 08:30:41

标签: java angularjs rest

大家好我正在使用angularjs java和rest来实现一个报告。根据选择的UI字段,调用Java Layer,从java中有一些数据库调用,我在csv文件中下载返回的输入流。 有一个问题发生,如果我做同样的浏览器使用相同的URL浏览我通过angularjs而不是我能够下载文件但是如果通过使用UI我发出请求比没有下载选项和数据返回为http响应angular的流。

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}使我能够下载文件。

1 个答案:

答案 0 :(得分:0)

您可以在angularjs代码中使用Blob,如下所示:

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