java图片保存文件到数据库_java保存图片内容到数据库

本文使用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 tdl=new ThreadLocal();

//静态代码块,保证得到的连接是唯一的

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文件配置

index.jsp

ShowImgAction

com.test.action.img.ShowImgAction

ShowImgAction

/showImg

jsp显示图片

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

显示数据库的图片

图片:  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值