从数据库中读取并生成图片的Servlet


由于图片的binary码很大,这里在sql server2005数据库字段设计时采用varBinary(Max)而具体操作需要借助于java.IO(Input/Output)技术来实现.

基本思路

1.创建ServletOutputStream对象out,用于以字节流的方式输出图像
2.创建InputStream in,获取数据库中流
3.创建byte数组用作缓冲,将in读入buf[],
4.由out输出 ,jsp页面获取图片。


代码案例:
//dept.deptIcon是byte[],直接从数据库中读取,因此可以直接out
ServletOutputStream sout = response.getOutputStream();
sout.write(dept.getDeptIcon());// 将缓冲区的输入输出到页面
sout.flush(); // 输入完毕,清除缓冲
sout.close();

当没有部门图标默认处理
ServletOutputStream sout = response.getOutputStream();
InputStream in = new FileInputStream( new File(request
						.getRealPath("/images/noGpj.gif"));	

byte buf[]=new byte[1024]; 
int len=0;
while ((len=in.read(buf,0,1024))!=-1) { 
	sout1.write(buf,0,len); 
} 				
sout1.flush(); // 输入完毕,清除缓冲
sout1.close();

你可能感兴趣的:(sql,jsp,servlet)