通过调用spring rest api使用angular js下载文件

时间:2014-12-09 09:39:52

标签: angularjs download

我有一个Spring Controller,它会在响应中发送文件

@RequestMapping(value = "/downloadData", method = RequestMethod.GET)
public void downloadData(HttpServletResponse response) throws IOException
{
    File dataJSONFile = dataDownloadService.createAndWriteFile();
    response.setContentType("application/text");
    response.setContentLength(new Long(dataJSONFile.length()).intValue());
    response.setHeader("Content-Disposition", "attachment; filename="data.json");
    FileCopyUtils.copy(new FileInputStream(dataJSONFile),     
    response.getOutputStream());
}

如果我在浏览器网址中写,//localhost:8080/myproject/rest/downloadData它会下载文件。

现在,想要在使用angular js时点击按钮下载文件。

我在angular js中编写了以下代码来下载文件

angular
    .module('myApp.services')
    .factory(
            'DataDownloadService',
            function($resource) {
                "use strict";
                return {
                    "query" : function() {
                        var ret, restResource;
                        restResource = $resource(
                                '/sand-pp/api/rest/downloadData',
                                {}, {
                                    "query" : {
                                        "method" : "GET",
                                        "isArray" : true,
                                        headers:
                                        {
                                            'Content-Type': 'application/text',
                                            'Content-Disposition': 'attachment; filename=data.json'

                                        }
                                    }
                                });
                        ret = restResource.query();
                        return ret;
                    }
                };
            });

当我调用上述服务时,没有任何事情发生,但如果我在回调函数中打印数据是在控制台中打印数据。 如何通过调用Spring REST API来下载角度js中的文件?

1 个答案:

答案 0 :(得分:0)

我会为休息电话使用服务。请尝试以下方法:

window.location.href = DataDownloadService.query();

它应该提示浏览器下载文件(因为Content-Disposition标题)。