Spring - 下载文件并重定向 [英] Spring - download file and redirect

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

问题描述

我的网页上有一个下载链接,它的工作原理很好,但不会刷新/重定向我的页面。这是我的代码。

I have a download link on my page which works just fine but it doesn't refresh/redirects my page. Here's my code.

@RequestMapping(method = RequestMethod.POST, params = "exportToXML")
public String exportToXML(HttpServletResponse response, Model model, @ModelAttribute(FILTER_FORM) ScreenModel form,
        BindingResult result, OutputStream out,
        HttpSession session) throws IOException {
    ZipOutputStream zipout;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();


        zipout = new ZipOutputStream(baos);
        ZipEntry ze = new ZipEntry("file.xml");
        zipout.putNextEntry(ze);
        zipout.write(string.getBytes());
        zipout.closeEntry();
        zipout.close();
        baos.close();


    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=xx.zip");
    response.getOutputStream().write(baos.toByteArray());
    response.getOutputStream().close();
    response.getOutputStream().flush();
    return VIEW_NAME;
}

我删除了不相关的代码段,使其稍短一些。我也尝试过@ResponseBody,但它给出与上面代码相​​同的结果。
任何建议将会有帮助

I've removed irrelevant pieces of code to make it a little bit shorter. I have also tried with @ResponseBody but it gives the same result as code above. Any advice will be helpful

推荐答案

您无法下载文件并进行刷新/重定向。
我会尝试解释原因。请求流程如下所示:

You can't download file and make refresh/redirect. I'll try to explain causes. Request flow is illustrated here:

其中黄色圆圈是您的控制器。当您返回视图名称前端控制器查找适当的视图模板(简单的jsp,tile或其他,根据配置的视图解析器)获取响应并写入生成的html(或不是html)代码。

where yellow circle is your controller. When you return view name front controller looks for appropriate view template (simply jsp, tiles or other, depending on configured view resolver) gets response and write generated html (or not html) code to it.

在您的情况下,您执行操作:

In your case you perform actions:

response.getOutputStream().write(baos.toByteArray());
response.getOutputStream().close();
response.getOutputStream().flush();

之后的操作弹簧无法打开响应并写入刷新页面(因为您之前这样做) )。
所以你可以改变你的方法签名:

After that actions spring can't open response and write refreshed page to it (because you do it before). So you can change your method signature to:

public void exportToXML(HttpServletResponse response, Model model, @ModelAttribute(FILTER_FORM) ScreenModel form,
        BindingResult result, OutputStream out,
        HttpSession session) throws IOException {

并删除最后一个返回VIEW_NAME。没有任何变化。

and delete last "return VIEW_NAME". Nothing will change.

这篇关于Spring - 下载文件并重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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