user8568444
user8568444

Reputation:

Redirect after downloading the pdf in spring

I'm using spring boot. I wrote code to upload data to database. If something goes wrong, data will be downloaded as a pdf which is wrong. What I want to do is, I have to download that pdf and direct to another page.

@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public void doUpload(@ModelAttribute("employeeCsvForm") EmpFileUpload fileUpload,HttpServletRequest request, HttpServletResponse response){

    // codes for create pdf.

    if (errorCount != 0) { //errorCount is the count of error data  

        File fileEmp = new File("error.pdf");

        //downloading the pdf in browser path
        if (fileEmp.exists()) {
            FileUtils.copyFile(fileEmp, response.getOutputStream());
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "attachment;filename=error.pdf");
            response.flushBuffer();             
        }   
    }
}

This code downloads the pdf file. But I have to redirect to another page, So I used

response.sendRedirect(request.getContextPath() + "/employee/errorCsv"); after response.flushBuffer(); Its downloading pdf successfully but showing following error.

Error is : getOutputStream() has already been called for this response

When I write the redirect code response.sendRedirect(request.getContextPath() + "/employee/errorCsv"); before response.flushBuffer(); Its directing to other page successfully but not downloading.

I want to do both, I tried my best, but failed. Thanks in advance.

Upvotes: 4

Views: 1913

Answers (1)

Jiri Tousek
Jiri Tousek

Reputation: 12450

You cannot redirect after you initiate a download.

That's why every page that redirects upon download (think Sourceforge for example) does this by:

  • first redirecting you to the target page
  • waiting a couple seconds (possibly optional, but might help load the target page)
  • then initiating a download using Javascript (for browser, this is in fact another redirect)

Technically, a HTTP redirect is part of HTTP headers. Headers are sent over HTTP before any actual content and cannot be sent once you start sending the body (content) - that's why you got the error.

To the browser, a download is just a special kind of page visit - one that ends up downloading data instead of showing it as a website. Now, you only can initiate a redirect (i.e. direct the browser to visit another page) in a website, you cannot do this if downloading. So the following order of steps cannot possibly work:

  • Visit initial page
  • At the initial page, direct browser to download file
  • Direct browser to visit target page

So what you have to do is swap the steps:

  • Visit initial website
  • At the initial page, direct browser to visit target page
  • At the target page, direct browser to download file

Upvotes: 2

Related Questions