春天 - 下载响应为文件 [英] Spring - download response as a file

查看:119
本文介绍了春天 - 下载响应为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写使用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?

下面,我贴我的简化code。
在Spring控制器:

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请求下载一个文件(这是怎么了角使的要求)。见<一href=\"http://stackoverflow.com/questions/14682556/why-threre-is-no-way-to-download-file-using-ajax-request\">Why threre是没有办法使用Ajax请求下载文件你要么需要通过 $ window.open 转到URL或做此处显示的iframe的伎俩:<?一个href=\"http://stackoverflow.com/questions/3499597/javascript-jquery-to-download-file-via-post-with-json-data/\">Javascript/jquery通过POST来下载文件,JSON数据

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

这篇关于春天 - 下载响应为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆