如何在jsp页面显示一个已有的word文档

2025-04-29 11:13:59
推荐回答(1个)
回答1:

<%@page contentType="application/msword;charset=utf8"%>
<%@page import="java.io.*"%>
<%
String filename = "";
if (request.getParameter("docfilename") != null) {
filename = request.getParameter("docfilename");
}
File f = new File(filename);
if(!f.exists() || f.isDirectory()){
out.println("");
out.close();
return;
}

response.setContentType("application/msword");
response.setHeader("Content-disposition","attachment; filename=mc.doc");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(filename));
bos = new BufferedOutputStream(response.getOutputStream());

byte[] buff = new byte[2048];
int bytesRead;

while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff,0,bytesRead);
}

} catch(FileNotFoundException fe){
System.out.println("文件没找到");
} catch(final IOException e) {
System.out.println ( "出现IOException." + e );
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
out.clear();
out = pageContext.pushBody();
}
return;
%>