[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<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>

 

Java,上传图片并保存到数据库可以通过以下步骤实现: 1. 创建一个包含图片信息的Java类,例如ImageInfo,其包含图片的名称、类型、大小等属性。 2. 创建一个用于处理文件上传的Servlet,例如UploadServlet。在该Servlet,可以使用Apache Commons FileUpload库来处理文件上传操作。 3. 在UploadServlet,获取上传的文件流,并将其保存到服务器的指定位置。可以使用File类来创建目标文件夹和文件,并使用FileOutputStream将文件流写入目标文件。 4. 将图片信息保存到数据库。可以使用JDBC或者ORM框架(如Hibernate、MyBatis)来操作数据库。根据ImageInfo类的定义,创建对应的数据库表,并将图片信息插入到表。 下面是一个简单的示例代码: ```java // ImageInfo.java public class ImageInfo { private String name; private String type; private long size; // 其他属性和方法 // getter和setter方法 } // UploadServlet.java @WebServlet("/upload") public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上传的文件流 Part filePart = request.getPart("file"); // "file"为前端表单文件上传字段的名称 InputStream fileInputStream = filePart.getInputStream(); // 保存文件到服务器指定位置 String fileName = filePart.getSubmittedFileName(); String filePath = "/path/to/save/" + fileName; // 指定保存路径 File targetFile = new File(filePath); FileOutputStream fileOutputStream = new FileOutputStream(targetFile); byte[] buffer = new byte[1024]; int length; while ((length = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, length); } fileOutputStream.close(); fileInputStream.close(); // 将图片信息保存到数据库 ImageInfo imageInfo = new ImageInfo(); imageInfo.setName(fileName); imageInfo.setType(filePart.getContentType()); imageInfo.setSize(filePart.getSize()); // 将imageInfo插入到数据库 // 返回上传成功的提示信息 response.getWriter().println("文件上传成功"); } } ``` 请注意,上述代码仅为示例,实际应用可能需要进行错误处理、文件大小限制、文件类型验证等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事随风ing

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值