Java 使用 JSF 在新的浏览器窗口中阅读和打开 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22103734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
read and open PDF in a new browser window with JSF
提问by Al2x
Java / JSF
Java/JSF
Im trying to open PDF in a new browser windowinstead of download it but in every try the file is downloaded with success and it opens a new tab with the application only and not the pdf file.
我试图在新的浏览器窗口中打开 PDF而不是下载它,但在每次尝试中,文件都会成功下载,它打开一个新选项卡,仅包含应用程序而不是 pdf 文件。
<p:commandLink title="report" target="_blank"
action="#{managedBean.generateReport('P',true)}"
ajax="false" immediate="false" >
</p:commandLink>
Managed bean: generateReport calls downloadFile
托管 bean: generateReport 调用 downloadFile
The filePath parameter below = /temp/doc/abc.pdf (chmod 777)
下面的 filePath 参数 = /temp/doc/abc.pdf (chmod 777)
public static void downloadFile(String filePath) throws IOException{
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally
{
input.close();
output.close();
}
context.responseComplete();
}
My Chromium plugin is enabled :
我的 Chromium 插件已启用:
采纳答案by Jalal Sordo
回答by BrianC
It has to be set to the PDF content type ("application/pdf") if you want the browser to know it is a PDF. You are setting it to "application/octet-stream".
如果您希望浏览器知道它是 PDF,则必须将其设置为 PDF 内容类型(“应用程序/pdf”)。您将其设置为“应用程序/八位字节流”。
回答by Teerawat
At this line
在这一行
response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
replace with
用。。。来代替
response.setHeader("Content-Disposition", "filename=\"" + file.getName() + "\"");
remove ==> attachment; then Pdf will open in new tab
删除 ==> 附件;然后 Pdf 将在新选项卡中打开