【问题标题】:Download file using angular js by calling spring rest api通过调用spring rest api使用angular js下载文件
【发布时间】:2014-12-09 09:39:52
【问题描述】:

我有一个 Spring 控制器,它发送文件作为响应

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

如果我在浏览器 url 中写入,//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 以 Angular js 下载文件?

【问题讨论】:

    标签: angularjs download


    【解决方案1】:

    我会使用服务来进行其余呼叫。试试这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2017-08-03
      • 1970-01-01
      相关资源
      最近更新 更多