Servlet直接打开pdf、doc、xls等文件。
setContentType设置MIME类型,Acrobat PDF文件为"application/pdf",WORD文件为:"application/msword",EXCEL文件为:"application/vnd.ms-excel"。setHeader设置打开方式,具体为:inline为在浏览器中打开,attachment单独打开。
详细参考:
如何用 servlet 打开非 HTML 格式的文档http://www-900.ibm.com/developerWorks/cn/java/jw-tips/tip094/index.shtml
以打开EXCEL文件为例,具体代码如下:
String sFileName = "test.xls";
resp.setStatus(200);
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-disposition", "inline;filename=\"" + sFileName + "\";");
ServletOutputStream sos = resp.getOutputStream();
sFileName = "Files/" + sFileName;
log("sFileName = " + sFileName);
FileInputStream fis = new FileInputStream(sFileName);
BufferedOutputStream bos = new BufferedOutputStream(sos);
byte[] bytes = new byte[8192];
for (int i=fis.read(bytes); i>0; i=fis.read(bytes))
{
bos.write(bytes, 0, i);
}
fis.close();
sos.close();
bos.close();
有机会要亲自试试
页:
[1]