我的页面上有一个下载链接,它工作得很好,但它不会刷新/重定向我的页面。这是我的代码。
@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 但它给出了与上面代码相同的结果。
任何建议都会有所帮助
最佳答案
您无法下载文件并进行刷新/重定向。
我会试着解释原因。请求流程如下所示:
其中黄色圆圈是您的 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/