把照片存到数据库

初学javaWeb的同学会遇见如何把照片上传到数据库里面的问题,我们要把照片存到数据库的话要进行如下几个步骤:

1.连接数据库 2.在数据库里面建好相应的表 3.写好增删改查照片的 mysql语句 这里我只写了增加照片,和查询照片的mysql语句。

工具说明 我用的是 Eclipse 开发工具 数据库是 mysql数据库

1.连接数据库

package com.jx.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbUtil {
    
    /**
     *
     * @DbUtil类的作用 jdbc 的一些简单配置
     * dbUrl
     * dbusername
     * dbpassword
     * jdbcName
     * @author 蒋鑫
     */

    private String dbUrl="jdbc:mysql://localhost:3306/mysql57";
    private String dbUserName="root";
    private String dbPassword="root";
    private String jdbcName="com.mysql.jdbc.Driver";
    
    /**
     * 获取数据库连接
     * @return
     * @throws Exception
     */
    public Connection getCon() throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
        return con;
    }
    
    /**
     * 关闭数据库连接
     * @param con
     * @throws Exception
     */
    public void closeCon(Connection con) throws Exception{
        if(con!=null){
            con.close();
        }
    }
    
    /**
     * 建立一个main方法测试是否可以连接数据库成功!
     * @param args
     * @author 蒋鑫
     */
    
    public static void main(String[] args) {
        DbUtil dbUtil=new DbUtil();
        try {
            dbUtil.getCon();
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

里面不仅有链接数据库的方法我还在最下面写了一个main方法进行单独测试。直接运行这个类就可以测试数据库有么有链接成功!

数据库连接成功后,我们开始编写 实际操作照片的代码。比如对数据库进行操作的DAO

package com.jx.dao;

import java.io.BufferedInputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.jx.util.DbUtil;

/*
 * 这个类的作用就是把图片添加进去,
 * 然后在从数据库把图片查找出来是blob类型
 * 然后放在一个文件夹的位置
 * @auther 蒋鑫
 */
public class DAO {
    
    // 添加图片
    public void insertImageInfo( byte[] img, String imageName) throws Exception {
        Connection conn = null;
        PreparedStatement pstm = null;
        DbUtil jdbc = null;
        StringBuffer sb = null;
        try {
            sb = new StringBuffer();
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            StringBuffer sql = sb.append(sql语句根据你自己的数据内容写,所以我删了写的mysql语句给你写个注释);
            pstm = conn.prepareStatement(sql.toString());
            pstm.setBytes(1, img); // 以字节数组的形式写入
            pstm.setString(2, imageName);
            pstm.setString(3, name);
            
            pstm.executeUpdate();
        } catch (Exception e) {
            throw new RuntimeException(e);

        }
    }
        //查询单个照片出来 类型blob
    public Blob selectOneImage(String name) throws Exception {
        BufferedInputStream bufferImage = null;
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        DbUtil jdbc = null;
        StringBuffer sb = null;
        Blob blob = null;
        try {
            sb = new StringBuffer();
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            StringBuffer sql = sb.append(sql语句根据你自己的数据内容写,所以我删了写的mysql语句给你写个注释);
            pstm = conn.prepareStatement(sql.toString());
            pstm.setString(1, name);
            rs = pstm.executeQuery();
            while (rs.next()) {
                // 必须强制类型转换
                blob = (Blob) rs.getBlob("image");
                // bufferImage = new BufferedInputStream(blob.getBinaryStream());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return blob;
    }

        //获得照片的名字
    public String getImageName(String name) throws Exception {
        BufferedInputStream bufferImage = null;
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        DbUtil jdbc = null;
        StringBuffer sb = null;
        try {
            sb = new StringBuffer();
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            StringBuffer sql = sb.append(sql语句根据你自己的数据内容写,所以我删了写的mysql语句给你写个注释 比如什么SELECT * FROM 什么的);
            pstm = conn.prepareStatement(sql.toString());
            pstm.setString(1, name);
            rs = pstm.executeQuery();
            while (rs.next()) {
                return rs.getString(1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

}


这是我的源码 还有我的数据库 表示这样写的  表面 image 列名是imageName 主键 非空 varchar 255 然后是blob 存放二进制文件的列。大家不管是什么数据库都可以建立一张这样的表格!还有这些方法是有参方法 所以在方法里面除了 byte[] img, 这个是一会要传二进制文件的参数 不要更改和删除以外其他东西都可以替换成自己的!

然后dao写好后!

我们要写个类调用这些dao(对数据库的操作)写个类能让前台调用这些dao。

package com.jx.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Scanner;

import com.jx.dao.DAO;

/**
 * 把图片按照路径存进去到数据库
 * saveImage 按照Email 存进去还有他的路径
 * @author    蒋鑫
 *
 */
public class ISaveImageServiceImpl {
    private static DAO saveImageDAO = new DAO();

    public static void saveImage(String Email, String imgPath,String imageName) throws Exception {
        Connection conn = null;
        DbUtil jdbc = null;
        int id=0;
        byte[] img = null;
        try {
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            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(Email,img,imageName);
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
    }

    public static Blob getImage(String Email) throws Exception {
        Connection conn = null;
        DbUtil jdbc = null;
        BufferedInputStream bg = null;
        Blob bg1=null;
        try {
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            conn.setAutoCommit(false);
            // 获取缓冲流
//            bg = saveImageDAO.selectOneImage(imgName);
            bg1=saveImageDAO.selectOneImage(Email);
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
        return bg1;
    }
    
    public String getImageName(String Email) {
        Connection conn = null;
        DbUtil jdbc = null;
        BufferedInputStream bg = null;
        String bg1=null;
        try {
            jdbc = new DbUtil();
            conn = jdbc.getCon();
            conn.setAutoCommit(false);
            // 获取缓冲流
//            bg = saveImageDAO.selectOneImage(imgName);
            bg1=saveImageDAO.getImageName(Email);
            conn.commit();
        } catch (Exception e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                throw new RuntimeException(e1);
            }
            throw new RuntimeException(e);
        }
        return bg1;
    }
    
    
//    测试用
    public static void main(String[] args) {
            Scanner input=new Scanner(System.in);
            System.out.println("请输入用户邮箱:");
            String Email=input.next();
            System.out.println("请输入图片正确地址:");
            String path=input.next();
            System.out.println("请输入图片名称:");
            String photoName=input.next();
            try {
                saveImage(Email,path,photoName);
                Blob bo=getImage(Email);
                BlobUtil k=new BlobUtil();
                k.ExportBlob("D:\\", "成功.jpg", bo);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
}

源码如下使用这个类的时候必须把照片往数据的添加和从数据查询的dao写好了

然后这个方面最下面就是一个测试main用来测试能不能把照片存进去和把照片查出来放在一个自己给定的地址。

我又看了一遍检查了一遍

最后还有这个类也要写上 这类的作用就是上面这个类最后  BlobUtil k=new BlobUtil();    k.ExportBlob("D:\\", "成功.jpg", bo); 用的把照片写到你电脑的上的一个位置,

package com.jx.util;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;

public class BlobUtil{
     public static void ExportBlob(String path,String fileName, Blob myBlob) throws Exception  
      {      
        File file=new File(path+"\\"+fileName);
        if(!file.exists()){
            File binaryFile = new File(path);
            if(!binaryFile.exists()){
                binaryFile.mkdirs();
            }
            FileOutputStream outStream = new FileOutputStream(binaryFile+"\\"+fileName);  
            InputStream inStream = myBlob.getBinaryStream();  
            int size=(int) myBlob.length();
            byte[] buffer = new byte[size];  
            int length = -1;  
          
            while ((length = inStream.read(buffer)) != -1)  
            {  
              outStream.write(buffer, 0, length);  
              outStream.flush();  
            }  
          
            inStream.close();  
            outStream.close();  
          }   
      }
}

好了总共是 dao数据库操作 链接数据库 调用数据库dao进行测试 还有一个把读取到了的二进制文件blob文件转换为图片格式的类一共是四个类。记得往数据库添加的时候建立一个数据库的其中一个要设置类型为 blob用来存粗照片的。应该没有什么难的核心代码我已经贴上去了 而且这些代码是一个全部项目源码。检查了俩边上面代码一个不少一个不漏 如果你没出什么错的话 应该直接可以用的。

猜你喜欢

转载自blog.csdn.net/qq_42499475/article/details/81355107