日期:2014-05-16  浏览次数:20716 次

Hibernate将文件二进制存入mysql
二进制大型对象(BLOB)列是MySQL的秘密武器之一。这些列中存储了二进制的数据,你可以象其它普通的数据类型一样来检索和操纵它。根据MySQL指南有关资料,BLOB是一个二进制大型对象,它能容纳不同大小的数据。事实上,MySQL有四种BLOB类型:

◆tinyblob:仅255个字符
◆blob:最大限制到65K字节
◆mediumblob:限制到16M字节
◆longblob:可达4GB

提示代码
String fname = "c:\\itanger.gif";//要入库的文件 
File f = new File(fname); 
FileInputStream fin = new FileInputStream(f); 
tad.setImage(Hibernate.createBlob(fin)); 


public void doGet(HttpServletRequest request,HttpServletResponse response){
        User user=(User)session.load(User.class, new Integer(1));
        Blob photo=user.getPhoto();
        InputStream in=photo.getBinaryStream();
        OutputStream out=response.getOutputStream();
        byte [] buf=new byte[1024];
        int len;
        while((len=in.read(buf))!=-1){
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }