1、情况是这样子的:读取一个本地的pdf文件,然后再页面上显示这个pdf文件,就相当于pdf预览的功能。
遇到的问题是:通过在标题头的设置,从页面上下载的pdf无法让pdf阅读器读取显示,并且在页面查看就显示:"无法加载Pdf文件"。
下载后的图片:
页面展示时的图片:
2、代码是这样子的:
String filePath=SealAction.getPdfPath(); //pdf文件的绝对路径
File outFile = new File(filePath);
if (!outFile.exists()) {
this.setMsg("文件不存在");
return EMPTY;
} else {
response.setContentLength((int)outFile.length());
response.setCharacterEncoding("utf-8");
response.setHeader("Content-type", "application/pdf;charset=utf-8");
String filename = outFile.getName();
response.addHeader("Content-Disposition","attachment;filename=" + new String(filename.getBytes(),"utf-8"));
FileInputStream fli = null;
OutputStream out = null;
BufferedReader in = null;
Writer oWriter = null;
//以流的方式响应会页面
try {
fli = new FileInputStream(outFile);
out = response.getOutputStream();
in = new BufferedReader(new InputStreamReader(fli,"UTF-8"));
oWriter = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
char[] b = new char[1024];
int i = 0;
while((i = in.read(b))!= -1)
{
oWriter.write(b, 0, i);
}
in.close();
oWriter.flush();
oWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
if(in != null){
in.close();
in = null;
}if(oWriter != null){
oWriter.close();
oWriter = null;
}
}catch(Exception e){
//不作任何处理
}
}
}
3、总的来说:问题是如何能在页面上显示出pdf呢? 哪里错了呢?