Reputation:
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
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:
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:
So what you have to do is swap the steps:
Upvotes: 2