Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - download file and redirect

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;
}

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

like image 941
xwhyz Avatar asked Aug 16 '13 13:08

xwhyz


2 Answers

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

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 {

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

like image 194
yname Avatar answered Sep 28 '22 01:09

yname


You can:

response.setHeader("Refresh", "1; url = index");

This refresh the page after 1 second after response on URL: "index".

like image 40
Atan Avatar answered Sep 28 '22 01:09

Atan