java保存图片内容到数据库

来源:互联网 发布:mac装microsoft office 编辑:程序博客网 时间:2024/06/14 12:38

本文使用mysql数据库举例插入图片到数据库和从数据库取出图片在页面显示:

一、建表

创建一个测试保存图片的表
create table t_save_img(
name varchar(200),   文件名称
img  longblob ,        
primary key(name)
)

二、建实体类:SaveImageInfo

private String name; //文件名称
private byte[] bt; //字节数组

三、数据源配置

db.properties文件

test.driver=com.mysql.jdbc.Driver
test.url=jdbc:mysql://127.0.0.1:3306/dg?CharacterEncoding=GBK
test.user=root
test.password=root


四、数据库连接的工具类

package com.test.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
 * 
 *@类功能说明:获取数据库连接和释放数据库连接的工具类
 *@修改人员名: yang
 *@修改日期:    2015-11-28 下午03:48:11
 *@修改内容:
 *@修改次数:
 *@创建时间:    2015-11-28 下午03:48:11
 *@版本:V1.0
 */
public class JdbcUtil {
private static Properties prop=new Properties();
private  final static ThreadLocal<Connection > tdl=new ThreadLocal<Connection>();
//静态代码块,保证得到的连接是唯一的
static{
try {
InputStream is=JdbcUtil.class.getResourceAsStream("/db/db.properties");
prop.load(is);
Class.forName(prop.getProperty("test.driver"));
} catch (Exception e) {
throw new RuntimeException(e);

}
//获取连接
public Connection getConn() throws Exception{
Connection conn=null;
try {
//获得当前数据库连接线程
conn=tdl.get();
conn=DriverManager.getConnection(prop.getProperty("test.url"), 

prop.getProperty("test.user"), prop.getProperty("test.password"));
tdl.set(conn);
} catch (SQLException e) {
throw new RuntimeException(e);
}
return conn;
}
//释放连接
public void releaseConn(Connection conn,PreparedStatement pstm,ResultSet rs)throws Exception{
try{
if(conn!=null){
tdl.remove();
conn.close();
}
if(pstm!=null){
pstm.close();
}
if(rs!=null){
rs.close();
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
}

五、开始实现保存图片和显示图片

DAO的代码如下:

package com.test.dao;
import java.io.BufferedInputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.test.util.JdbcUtil;
/**
 * 
 *@类功能说明:保存图片到数据库的实现类
 *@修改人员名: yang
 *@修改日期:    2015-11-28 下午04:28:07
 *@修改内容:
 *@修改次数:
 *@创建时间:    2015-11-28 下午04:28:07
 *@版本:V1.0
 */
public class ISaveImageToDataDAOImpl {
//添加图片
public void insertImageInfo(String name,byte[] img)throws Exception{
Connection conn=null;
PreparedStatement pstm=null;
JdbcUtil jdbc=null;
StringBuffer sb=null;
try{
sb=new StringBuffer();
jdbc=new JdbcUtil();
conn=jdbc.getConn();
StringBuffer sql=sb.append("insert into t_save_img values(?,?) ");
pstm=conn.prepareStatement(sql.toString());
pstm.setString(1, name);
pstm.setBytes(2, img); //以字节数组的形式写入
pstm.executeUpdate();
}catch(Exception e){
throw new RuntimeException(e);
}finally{
jdbc.releaseConn(null, pstm, null);
}
}
//获取图片
public BufferedInputStream selectOneImage(String name)throws Exception{
BufferedInputStream bufferImage=null;
Connection conn=null;
PreparedStatement pstm=null;
ResultSet rs=null;
JdbcUtil jdbc=null;
StringBuffer sb=null;
try{
sb=new StringBuffer();
jdbc=new JdbcUtil();
conn=jdbc.getConn();
StringBuffer sql=sb.append("select name,img from t_save_img where name=?  ");
pstm=conn.prepareStatement(sql.toString());
pstm.setString(1, name);
rs=pstm.executeQuery();
while(rs.next()){
//必须强制类型转换
Blob blob=(Blob)rs.getBlob("img");
bufferImage=new BufferedInputStream(blob.getBinaryStream());
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
jdbc.releaseConn(null, pstm, null);
}
return bufferImage;
}
}

service代码

package com.test.service;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.SQLException;
import com.test.dao.ISaveImageToDataDAOImpl;
import com.test.util.JdbcUtil;
public class ISaveImageServiceImpl {
private ISaveImageToDataDAOImpl saveImageDAO=new ISaveImageToDataDAOImpl();
public void saveImage(String name,String imgPath) throws Exception{
Connection conn=null;
JdbcUtil jdbc=null;
byte []img=null;
try{
jdbc=new JdbcUtil();
conn=jdbc.getConn();
conn.setAutoCommit(false);
File file=new File(imgPath);
//读入内存
FileInputStream  fis=new FileInputStream(file);
//建立缓冲区
ByteBuffer  bbf=ByteBuffer.allocate((int)file.length());
byte[]array=new byte[1024];
int length=0;
//开始读取和存放数据
while((length=fis.read(array))>0){
if(length!=1024){
bbf.put(array,0,length);
}else{
bbf.put(array);
}
}
//关闭输入流
fis.close();
//获取需要写的内容
img=bbf.array();
saveImageDAO.insertImageInfo(name, img);
conn.commit();
}catch(Exception e){
try {
conn.rollback();
} catch (SQLException e1) {
throw new RuntimeException(e1);
}
throw new RuntimeException(e);
}finally{
jdbc.releaseConn(conn, null, null);
}
}
public BufferedInputStream getImage(String imgName)throws Exception{
Connection conn=null;
JdbcUtil jdbc=null;
BufferedInputStream bg=null;
try{
jdbc=new JdbcUtil();
conn=jdbc.getConn();
conn.setAutoCommit(false);
//获取缓冲流
bg=saveImageDAO.selectOneImage(imgName);
conn.commit();
}catch(Exception e){
try {
conn.rollback();
} catch (SQLException e1) {
throw new RuntimeException(e1);
}
throw new RuntimeException(e);
}finally{
jdbc.releaseConn(conn, null, null);
}
return bg;
}
}

action获取图片的代码

package com.test.action.img;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.test.service.ISaveImageServiceImpl;
/**
 * 
 *@类功能说明:获取数据库图片,并且显示
 *@修改人员名: yang
 *@修改日期:    2015-11-29 上午10:29:26
 *@修改内容:
 *@修改次数:
 *@创建时间:    2015-11-29 上午10:29:26
 *@版本:V1.0
 */
@SuppressWarnings("serial")
public class ShowImgAction extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ISaveImageServiceImpl iis=new ISaveImageServiceImpl();
BufferedInputStream bis=null;
BufferedImage image = null;  
try{
//获取service中返回的缓冲流
bis=iis.getImage("da");
       image=ImageIO.read(bis);  
       //写给客户端,只能是静态图片jpg,png格式,不可为gif格式
       ServletOutputStream sos = response.getOutputStream();  
       JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);  
       encoder.encode(image); 
       bis.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

web.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- servlet在线显示图片 -->
  <servlet>
  <servlet-name>ShowImgAction</servlet-name>
  <servlet-class>com.test.action.img.ShowImgAction</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>ShowImgAction</servlet-name>
  <url-pattern>/showImg</url-pattern>
  </servlet-mapping>

</web-app>

jsp显示图片

<%@ page language="java" import="java.util.*" pageEncoding="GBK" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
  <head>
    <base href="<%=basePath%>">
    <title>显示数据库的图片</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">
  </head>
  <body>
   <font>图片:</font><img  src="${pageContext.request.contextPath}/showImg" width="130px" height="136px;">
  </body>
</html>


1 0
原创粉丝点击