在WEB应用中是不能直接访问本地文件,通常都是放到工程之中。
但是如果项目上线,从服务器上获取文件,那就不得不用io流去进行传输读取了。
最近,碰到一个问题,就是虽然用io流将图片读取到jsp页面了,但是无法使其居中。
我的java代码写在jsp,然后没办法了,将代码放入action中,最终图片读取出来并且居中显示了,但是总是报:Stream Closed io异常!
最后,全部删除了,回过头来还是jsp里边搞吧!!!
1.创建展示图片的jsp-->ShowPicture.jsp
<body>
<div align="center">
<img src="<%=request.getContextPath()%>/jsp/picture.jsp?filepath=<%=request.getParameter("filepath")%>&filetype=<%=request.getParameter("filetype")%>" />
</div>
2.ShowPicture.jsp调用的picture.jsp
<%@ page import="java.util.*,java.io.*">
<%
out.clear();
out = pageContext.pushBody();
//response.setContentType("application/pdf");
try {
String strPdfPath = new String(request.getParameter("filepath"));
String strfiletype = new String(request.getParameter("filetype"));
//判断是pdf文件还是jpg文件
if(strfiletype!=null && !strfiletype.equals("")){
if(strfiletype.equals("pdf")){
response.setContentType("application/pdf;charset=GB2312");
}else if(strfiletype.equals("jpg")){
response.setContentType("image/gif;charset=GB2312");
}
}
//判断该路径下的文件是否存在
File file = new File(strPdfPath);
if (file.exists()) {
DataOutputStream temps = new DataOutputStream(response
.getOutputStream());
DataInputStream in = new DataInputStream(
new FileInputStream(file));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
} else {
out.print(strPdfPath +"文件不存在!");
}
} catch (Exception e) {
out.println(e.getMessage());
}
%>