使用ANGULARJS从Jersey rest api调用文件下载/保存。文件附带响应为" Content-Disposition"

时间:2015-10-20 19:01:16

标签: java angularjs rest csv jersey

我是角色的新手。我作为附件作为附件返回CSV文件的hava java rest api "内容 - 处置","附件;文件名=" | content-type:application / octet-stream

现在,当我使用$ http从AngularJS调用此api时,我收到了响应.data ="" (空白)

我正在使用安全性的基本授权,因此我必须在调用API时传递Header,因此无法使用链接点击或新窗口打开CSV下载。

测试当我删除授权并在浏览器中点击url然后正在下载CSV文件时。在服务器端没有问题。

我需要在angularjs端帮助从web api响应中下载CSV文件作为附件。

这是我的Java API代码

public class ServiceAPI {

@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFileAsCSVFile(){

byte[] file=null;
    try {
        ArrayList<> List=new ArrayList<>();// data retrieved from DB 

        if(null != List){
             file=convertJsonToCSV(new Gson().toJson(List));

        }

    } catch (ParseException e) {


        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return            Response.ok(getBytes(file),MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", "attachment; filename=" + "FileName.csv").build();
 }
 }

和Angular代码:

app.controller('review', ['$scope', '$http',  function ($scope, $http){



$scope.fromDate = new Date();
$scope.toDate = new Date();


$scope.minDate = new Date(
    $scope.fromDate.getFullYear(),
    $scope.fromDate.getMonth() - 2,
    $scope.fromDate.getDate(),

    $scope.toDate.getFullYear(),
    $scope.toDate.getMonth() - 2,
    $scope.toDate.getDate()
);

$scope.maxDate = new Date(
    $scope.fromDate.getFullYear(),
    $scope.fromDate.getMonth() - 2,
    $scope.fromDate.getDate(),

    $scope.toDate.getFullYear(),
    $scope.toDate.getMonth() - 2,
    $scope.toDate.getDate()
);

$scope.reviews = json;


function openSaveAsDialog(filename, content, mediaType) {
    var blob = new Blob([content], {type: mediaType});
    saveAs(blob, filename);
}

function callApi(url) {

   // var dat=apiFactory.getServiceData(url);
   // console.log(dat);
   // apiFactory.getServiceData(url);

    var responseType='arraybuffer';
    var expectedMediaType='application/octet-stream';
    $http.get(url, {

        headers: {

            accept: expectedMediaType
        },
        responseType:responseType,
        cache: true,
        transformResponse: function (data) {
            var pdf;
            if (data) {
                pdf = new Blob([data], {
                    type: expectedMediaType
                });
            }
            return {
                response: pdf
            };
        }
    }).then(function (data,status,headers) {
        var filename='Preview.csv',
            octetStreamMime = "application/octet-stream",
            contentType;

        headers = data.headers();
        contentType = headers["content-type"] || octetStreamMime;


     //   openSaveAsDialog(filename, response.data, expectedMediaType);
        if (navigator.msSaveBlob) {
            var blob = new Blob([data], { type: contentType });
            navigator.msSaveBlob(blob, filename);
        } else {
            var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;

            if (urlCreator) {
                // Try to use a download link
                var link = document.createElement("a");

                if ("download" in link) {
                    // Prepare a blob URL
                    var blob = new Blob([data.data], { type: contentType });
                    var url = urlCreator.createObjectURL(blob);

                    link.setAttribute("href", url);
                    link.setAttribute("download", filename);

                    // Simulate clicking the download link
                    var event = document.createEvent('MouseEvents');
                    event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                    link.dispatchEvent(event);
                } else {
                    // Prepare a blob URL
                    // Use application/octet-stream when using window.location to force download
                    var blob = new Blob([data], { type: octetStreamMime });
                    var url = urlCreator.createObjectURL(blob);
                    $window.location = url;
                }
            }
        }
    });

};
    $scope.submit = function (fromDate, toDate) {


       $scope.url = API_url;


        var resp =callApi(($scope.url).split(" ").join("%20"));

        console.log(resp);
    };
},
]);

1 个答案:

答案 0 :(得分:4)

我有一个使用spring MVC而不是JAX-RS(Jersey)的例子

<强> HTML:

$scope.downloadCsv = function () {
    console.log("downloadCsv");
    var fileName = "test.csv";
    var a = document.createElement("a");
    document.body.appendChild(a);
    XxxxxxServiceCSV.downloadCsv().then(function (result) {
        console.log("downloadCsv callback");
        var file = new Blob([result.data], {type: 'application/csv'});
        var fileURL = URL.createObjectURL(file);
        a.href = fileURL;
        a.download = fileName;
        a.click();
    });
};

Angularjs controler:

angular.module('xxxxxxxxApp')
    .factory('XxxxxxServiceCSV', function ($http) {
        return {
            downloadCsv: function () {
            return $http.get('api/downloadCSV', { responseType: 'arraybuffer' }).then(function (response) {
                return response;
            });
        }
    };
});

Angularjs服务:

@RequestMapping(value = "/downloadCSV", method = RequestMethod.GET, produces = "application/csv")
public void demo(HttpServletResponse response) throws IOException {
    List<String> names = new ArrayList<String>();
    names.add("First Name");
    names.add("Second Name");
    names.add("Third Name");
    names.add("Fourth Name");
    BufferedWriter writer = new BufferedWriter(response.getWriter());
    try {
        response.setHeader("Content-Disposition", "attachment; filename=\"test.csv\"");
        for (String name : names) {
            writer.write(name);
            writer.write(",");
        }
        writer.newLine();
    } catch (IOException ex) {
    } finally {
        writer.flush();
        writer.close();
    }
}

Java代码JAX-RS(spring MVC):

sudo
相关问题