之前在做一个项目时用到了图片上传并立即展示到页面浏览,而且图片存放在硬盘上的一个文件夹中而非在工程与数据库中,这就会出现一个问题,如果不是在开发程序环境中访问图片页面,则会出现图片不能展示情况,原因很明显,就是外部无法访问到服务器硬盘上的图片。所以这时就需要用到i/o流读取图片并展示,以下是具体步骤:
1.图片展示页面showImg.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>i/o流读取图片</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script src="local/communication/static/jquery.min.js" charset="utf-8"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div>
<img id="viewImg2" src="local/communication/db/img.jsp?flag=zheng" style="height:90px;width:200px;" >
</div>
</body>
</html>
2.通过jsp页面服务读取图片,imp.jsp代码:
<%@ page language="java" import="java.util.*,java.util.Map.Entry,java.text.SimpleDateFormat,java.util.Date,net.sf.json.JSONArray,net.sf.json.JSONObject,java.net.URLEncoder,java.net.URLDecoder" pageEncoding="utf-8"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.OutputStream,java.io.FileOutputStream,java.io.IOException,java.io.FileInputStream,java.io.PrintWriter," %>
<%
request.setCharacterEncoding("UTF-8");
response.setContentType("image/png");
response.setHeader("Content-Disposition","attachment;Filename=test.png");
BufferedOutputStream bos = null;
InputStream fis = null;
BufferedInputStream bis = null;
String flag=request.getParameter("flag")==null?"":request.getParameter("flag");
try{
String tPath="D://img/11.jsp";
bos = new BufferedOutputStream(response.getOutputStream());
fis = new FileInputStream(tPath);
bis = new BufferedInputStream(fis);
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(buff, 0, bytesRead);
}
bos.flush();
}catch(Exception e){
}finally{
if(bos!=null){
bos.close();
}
if(bis!=null){
bis.close();
}
if(fis!=null){
fis.close();
}
}
out.clear();
out = pageContext.pushBody();
%>