Hibernate实现将图片保存至数据库、显示在页面

来源:互联网 发布:南阳炳盛网络 编辑:程序博客网 时间:2024/05/09 02:04

一般而言我们并不推荐将图片保存至数据库,通常的做法是将图片上传至服务器的某个路径,然后在数据库中存储它的路径。但是有时候某些需求必须要将图片保存至数据库,例如多个项目共享一个数据库,这时我们就只能把图片文件上传保存到数据库中了。

在Oracle数据库中我一般都是使用Blob字段来存储二进制文件的,所以要将图片存储到Oracle数据库中,图片字段必须为Blob。同时在Java中的Hibernate提供了非常存储机制,同时这个存储机制对二进制Blob支持非常棒。实现代码如下:

1234567891011121314151617181920212223242526
Blob blob = BlobUtils.file2Blob(file);   //将File转换为blob    advertisement.setImage(blob);     //入库处理    dao.saveOrUpdate(advertisement);     public static Blob file2Blob(File file) throws IOException, SerialException, SQLException {        InputStream is = null;        Blob blob = null;        try {            is = new FileInputStream(file);            byte[] content = new byte[is.available()];             is.read(content);            blob = new SerialBlob(content);        } catch (IOException e) {            throw e;        }finally{            if(is != null){                is.close();            }            if(file != null){                file.delete();            }        }        return blob;    }

在这段代码中首先是将File转换为Blob(Java.sql.Blob),然后通过Hibernate的save()方法进行保存。这段简单的代码就可以实现将图片存储到Oracle数据库中。下面将展示如下在数据看看中将图片取出来。

123456789101112131415161718192021222324
//将图片显示在页面-----servlet            Blob blob = advertisement.getImage();                int length = (int)blob.length();     //取得流中的可用字节总数                     byte[] buf = blob.getBytes(1,length);   //获取Blob字节数组                     response.setContentType("image/jpeg");                     OutputStream out = response.getOutputStream();//获取输出流                     for (int i = 0; i < buf.length; i++) {                         out.write(buf[i]);//输出到页面                     }                     out.close();//关闭输出流                         //将文件保存在服务器路径             Blob blob = advertisement.getImage();            InputStream is = blob.getBinaryStream();              FileOutputStream fos = new FileOutputStream("D://advertisementImage.jpg");              byte[] buffer = new byte[1024];              int len = 0;              while((len = is.read(buffer) )!= -1){                   fos.write(buffer,0,len);              }              System.out.println("成功处理完毕");              is.close();             fos.close();

当然通过Hibernate非常容易实现图片的存储和获取显示,没有什么技术含量。在这里只是起到一个记录的作用!!!!

0 0
原创粉丝点击