Content-Disposition attachment doesn't work - prints bits to screen
I'm trying to download a PDF file in Struts Action class. Problem is that using
response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
I want to open box for "save/open", but now PDF content is writen in browser: ex.
%PDF-1.4 28 0 obj << /Type /XObject /Subtype /Image /Filter /DCTDecode /Length 7746 /Width 200 /Height 123 /BitsPerComponent 8 /ColorSpace /DeviceRGB >>...(cut)
I was trying this code (below) under Chrome, Firefox and IE and everywhere this same. Also I was using different PDF files for that.
My code fragment:
try {
URL fileUrl = new URL("file:///" + filePath);
URLConnection connection = fileUrl.openConnection();
inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
byte[] outputStreamBytes = new byte[100000];
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
response.setContentLength(fileLength);
outputStream = response.getOutputStream();
int iR;
while ((iR = inputStream.read(outputStreamBytes)) > 0) {
outputStream.write(outputStreamBytes, 0, iR);
}
return null;
} catch (MalformedURLException e) {
logger.debug("service", "An error occured while creating URL object for url: "
+ filePath);
response.sendError(HttpServletRes开发者_如何学编程ponse.SC_NOT_FOUND);
return null;
} catch (IOException e) {
logger.debug("service", "An error occured while opening connection for url: "
+ filePath);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} finally {
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
inputStream.close();
}
return null;
Is something still missing?
EDIT
When I use this code in the Struts class it does not work, but when I use this code in the Servlet it is working. The strangest thing is that when I in action class write only "response.sendRedirect()" to Servlet (and all logic is in Servlet) it is not working too.
When I analyzed the response headers everything in these three examples is the same.
Try changing the Content-Type header to something not recognizable by the browser. Instead of
response.setContentType("application/pdf");
use
response.setContentType("application/x-download");
This will prevent the browser from acting upon the content of the body (which includes the handling of the content by plugins), and will force the browser to display the 'Save File' dialog box.
Additionally, it might also be useful to verify if the presence of a single whitespace after the semicolon in the Content-Disposition header, is necessary to trigger the required behavior. Therefore, instead of the following line
response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
use the following instead.
response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
精彩评论