Spring - 将响应下载为文件 [英] Spring - download response as a file
问题描述
我正在使用 AngularJS 和 Spring 编写应用程序.我想向服务器发送请求并下载从控制器返回的响应作为文件.在控制器中,我有 csv 文件的内容(作为字符串),即 1;2;3;4
(1 行,4 列).将此响应下载为文件的最简单方法是什么?
I am writing application using AngularJS and Spring. I would like to send request to the server and download response returned from controller as a file. In controller I have content of csv file (as string) i.e. 1;2;3;4
(1 row, 4 columns). What is the simplest way to download this response as a file?
下面,我发布了我的简化代码.在弹簧控制器中:
Below, I posted my simplified code. In Spring controller:
@RequestMapping(value = "/csv", method = GET)
@ResponseBody
public String getCsvFile() {
return getCsvContent();
}
在 JavaScript (AngularJS) 中
In javascript (AngularJS)
return $http({method: 'GET', url: 'csv/'});
我也试图写入响应流(如下),设置标头,但在客户端,我总是将此内容作为字符串获取 - 而不是作为要下载的文件.
I was trying to write to the response stream also (below), setting headers, but on client side I always get this content as a string - not as a file to download.
@RequestMapping(value = "/csv", method = GET)
@ResponseBody
public void getCsvFile(HttpServletResponse response) {
response.setContentType("application/csv");
response.setHeader("Content-Disposition", "attachment; filename=file.csv");
response.setContentLength(getCsvContent().getBytes().length);
ServletOutputStream out = response.getOutputStream();
out.write(getCsvContent());
out.flush();
out.close();
}
有谁知道如何正确编写控制器的方法以便将响应作为文件下载到客户端?
Does anyone knows how to write controller's method correctly in order to download response as a file on client side?
推荐答案
您不能通过 XHR 请求(这是 Angular 发出请求的方式)下载文件.请参阅为什么无法使用以下方法下载文件ajax 请求?您要么需要通过 $window.open
转到 URL,要么执行此处显示的 iframe 技巧:JavaScript/jQuery 使用 JSON 数据通过 POST 下载文件
You can't download a file through an XHR request (which is how Angular makes it's requests). See Why threre is no way to download file using ajax request? You either need to go to the URL via $window.open
or do the iframe trick shown here: JavaScript/jQuery to download file via POST with JSON data
这篇关于Spring - 将响应下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!