【发布时间】: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 下载文件?
【问题讨论】: