【发布时间】:2017-12-22 19:19:59
【问题描述】:
我尝试使用 Ajax 和 jquery 下载远程 URL 下可用的 CSV 文件(我不想重新加载视图,只想下载文件)。
问题是,该文件根本没有下载,这让我有点困惑。下面是我如何调用应该下载文件的 GET 端点:
<script>
$("#downloadBtn").click(function() {
$.get("${pageContext.request.contextPath}/download?path="+path);
});
<script>
这是负责处理该请求的控制器:
@GetMapping("/download")
public void downloadCsv(HttpServletResponse response, @RequestParam(required = true) String path) {
try {
URL url = new URL(path);
response.setHeader("Content-disposition", "attachment;filename=" + FilenameUtils.getName(url.getPath()));
response.setContentType("text/csv");
InputStream is = url.openStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ( (len = is.read(buf)) > 0 ) {
outs.write(buf, 0, len);
}
outs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我的控制器中的代码基本上是指这个 SO 问题: How to download file from url using Spring MVC?
我只是想知道为什么一旦 GET 请求完成,我就看不到任何下载的文件。对此有什么想法吗?
【问题讨论】:
-
您可以尝试使用 ["application/octet-stream"] 内容类型吗?
标签: jquery spring csv http spring-mvc