我正在尝试在Struts Action类中下载PDF文件。 问题是使用
response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
我想打开“保存/打开”框,但现在PDF内容在浏览器中写入: 离。
%PDF-1.4 28 0 obj << /Type /XObject /Subtype /Image /Filter /DCTDecode /Length 7746 /Width 200 /Height 123 /BitsPerComponent 8 /ColorSpace /DeviceRGB >>...(cut)
我在Chrome,Firefox和IE下尝试此代码(如下所示)并且到处都是这样。我也使用不同的PDF文件。
我的代码片段:
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(HttpServletResponse.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;
还有什么东西丢失了吗?
修改
当我在Struts类中使用此代码时,它不起作用,但是当我在Servlet中使用此代码时它正在工作。 最奇怪的是,当我在action类中只将“response.sendRedirect()”写入Servlet(并且所有逻辑都在Servlet中)时,它也不起作用。
当我分析响应头时,这三个例子中的所有内容都是相同的。
答案 0 :(得分:5)
尝试将Content-Type标题更改为浏览器无法识别的内容。而不是
response.setContentType("application/pdf");
使用
response.setContentType("application/x-download");
这将阻止浏览器对正文内容(包括插件处理内容)进行操作,并强制浏览器显示“保存文件”对话框。
此外,验证在Content-Disposition标头中分号后是否存在单个空格对于触发所需行为也是有用的。因此,而不是以下行
response.setHeader("Content-Disposition", "attachment;filename=file.pdf");
请改用以下内容。
response.setHeader("Content-Disposition", "attachment; filename=file.pdf");