Spring - 下载文件并重定向

标签 spring redirect spring-mvc download zip

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

@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 但它给出了与上面代码相​​同的结果。
任何建议都会有所帮助

最佳答案

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

其中黄色圆圈是您的 Controller 。当您返回 View 名称时,前端 Controller 查找适当的 View 模板(简单的 jsp、tile 或其他,取决于配置的 View 解析器)获取响应并将生成的 html(或非 html)代码写入其中。

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

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

在那之后,spring 无法打开响应并向其写入刷新的页面(因为您之前这样做过)。
因此,您可以将方法签名更改为:
public void exportToXML(HttpServletResponse response, Model model, @ModelAttribute(FILTER_FORM) ScreenModel form,
        BindingResult result, OutputStream out,
        HttpSession session) throws IOException {

并删除最后一个“返回 VIEW_NAME”。什么都不会改变。

关于Spring - 下载文件并重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275043/

相关文章:

spring - 在 Spock 规范中注入(inject)时,WebApplicationContext 不会 Autowiring

spring - 克服 Spring Boot 3 中缺少 SocketUtils 的问题

node.js - 带有请求的 jasmine-node - 测试重定向的端点不遵循重定向

Laravel 5.2如何将所有404错误重定向到首页

java - 无法获得特定情况 415(不支持的媒体类型)Angularjs 帖子的答案

java - 当我为json添加配置时,Spring MVC应用程序中断

java - RememberMeAuthenticationFilter 的 Spring Security authenticationSuccessHandler

java - 在 aspect 中读取注释属性

http - 为什么我不能设置 cookie 和重定向?

java - Spring:对构造函数\setter注入(inject)的循环依赖