问题
Java / JSF
Im trying to open PDF in a new browser window instead 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.
<p:commandLink title="report" target="_blank"
action="#{managedBean.generateReport('P',true)}"
ajax="false" immediate="false" >
</p:commandLink>
Managed bean : generateReport calls downloadFile
The filePath parameter below = /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 :

回答1:
How about primefaces media
:
From the showcase :
<p:media value="/resources/other/guide.pdf" width="100%" height="300px"/>
Also you can put this PDF viewer in a p:dialog
here.
回答2:
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".
回答3:
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
来源:https://stackoverflow.com/questions/22103734/read-and-open-pdf-in-a-new-browser-window-with-jsf