Spring - 下载文件并重定向

xwh*_*hyz 5 zip redirect spring spring-mvc download

我的页面上有一个下载链接,工作正常,但它不刷新/重定向我的页面.这是我的代码.

@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;
}
Run Code Online (Sandbox Code Playgroud)

我删除了不相关的代码片段,使其缩短了一点.我也试过@ResponseBody,但它给出了与上面代码相​​同的结果.任何建议都会有所帮助

yna*_*ame 8

您无法下载文件并进行刷新/重定向.我会试着解释原因.请求流程如下所示: 在此输入图像描述

黄色圆圈是你的控制器.当您返回视图名称时,前端控制器会查找相应的视图模板(只需jsp,tiles或其他,具体取决于已配置的视图解析程序)获取响应并将生成的html(或非html)代码写入其中.

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

response.getOutputStream().write(baos.toByteArray());
response.getOutputStream().close();
response.getOutputStream().flush();
Run Code Online (Sandbox Code Playgroud)

在该操作之后,spring无法打开响应并将刷新的页面写入其中(因为您之前执行过此操作).因此,您可以将方法签名更改为:

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

并删除最后一个"返回VIEW_NAME".什么都不会改变.