图片在数据库中的存取

MySQL中BLOB字段类型介绍

MySQL中,BLOB是个类型系列,BLOB类型的字段用于存储二进制数据包括:TinyBlob、Blob、MediumBlob、LongBlob,这几个类型之间的唯一区别是在存储文件的最大大小上不同。MySQL的四种BLOB类型     

类型 大小(单位:字节)
TinyBlob最大  255
 Blob 最大 65K
MediumBlob最大 16M
LongBlob 最大 4G

script.sql

create table tblUser
(uid int auto_increment primary key,
 uimage mediumblob);


 

public class ImageTest 
{

	@Test
	public void testSave() 
	{
		try 
		{
		    //FileInputStream 从文件系统中的某个文件中获得输入字节
		    //FileInputStream 用于读取诸如图像数据之类的原始字节流
			InputStream is = new FileInputStream("/home/soft02/Test/4.jpg");
			byte[] image=new byte[is.available()];
			//从此输入流中将最多 iamge.length 个字节的数据读入一个 byte 数组中
			is.read(image);
			is.close();
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn=DriverManager.getConnection("jdbc:mysql://10.0.5.98:3306/test","root","root");
			PreparedStatement stat=conn.prepareStatement("insert into tblUser (uimage) values (?)");
			stat.setBytes(1,image);
			stat.executeUpdate();
			
			stat.close();
			conn.close();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		

	}
}

public class ImageAction implements Action 
{
	private int imageid;
	
	public int getImageid() 
	{
		return imageid;
	}

	public void setImageid(int imageid) 
	{
		this.imageid = imageid;
	}

	public String execute() throws Exception 
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		ServletOutputStream sos=response.getOutputStream();
		byte[] image=null;
		
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn=DriverManager.getConnection("jdbc:mysql://10.0.5.98:3306/test","root","root");
		Statement stat=conn.createStatement();
		ResultSet rset=stat.executeQuery("select uimage from tblUser where uid="+imageid);
		if(rset.next())
			image=rset.getBytes("uimage");
		rset.close();
		stat.close();
		conn.close();
		
		sos.write(image);
		return null;
	}

}
struts.xml
      <action name="readimage" class="itany.action.ImageAction"/>

index.jsp

<!-- index.jsp?imgid=1 -->
<a href="success.jsp"><img src="readimage.itany?imageid=${param.imgid}"/></a>



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值