繁体   English   中英

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

[英]File download/save from a Jersey rest api call using ANGULARJS . file is attached with response as “Content-Disposition”

我是有角的新手。我有java rest api,它以附件形式返回CSV文件作为附件。 “ Content-Disposition”,“附件; filename =” | 内容类型:应用程序/八位字节流

现在,当我使用$ http从AngularJS调用此api时,我正在获取response.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();
 }
 }

和角度代码:

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);
    };
},
]);

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

HTML:

<button ng-click="downloadPdf()" class="btn btn-primary">download PDF</button>

Angularjs控制器:

$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服务:

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

Java代码JAX-RS(spring MVC):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM