【问题标题】:Downloading CSV in Spring MVC application - file doesn't download.在 Spring MVC 应用程序中下载 CSV - 文件未下载。
【发布时间】: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 请求完成,我就看不到任何下载的文件。对此有什么想法吗?

【问题讨论】:

标签: jquery spring csv http spring-mvc


【解决方案1】:

我在this SO question 中找到了非常适合我的解决方案(这是 Sean Carroll 提到的那个)。

<script>
    window.location="${pageContext.request.contextPath}/download?path="+path
<script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2021-03-07
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多