通过使用以下代码打开PDF文件,我只是将文件写入servlet的输出流,但是,当我尝试打开该PDF文件时,它显示错误:“不是pdf或已损坏”< / p>
我的代码:
public void displayPj() {
String url = ficheToDisplay.getUrl();
String outPutFile = ficheToDisplay.getNom();
HttpServletResponse resp = null;
resp = (HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
File file = new File(url);
resp.reset();
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ outPutFile + "\"");
resp.setContentType("application/pdf;charset=UTF-8");
resp.setHeader("Content-Length", String.valueOf(file.length()));
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
ServletOutputStream outStream = resp.getOutputStream();
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(resp.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
outStream.close();
} catch (Exception e) {
System.err
.println("PROBLEM STREAMING DAILY REPORT PDF THROUGH RESPONSE!"
+ e);
e.printStackTrace();
FacesMessage fm = new FacesMessage("Could Not Retrieve PDF.");
FacesContext.getCurrentInstance().addMessage(
"dailyReportArchiveFailure", fm);
}
FacesContext.getCurrentInstance().responseComplete();
}