使用 Blob 存储 和读取 图片

做个简单 图片上传和浏览的工具
使用 Blob 存储 和读取 图片_第1张图片

package com.enhance.jdbc.blob;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;


/*  创建 blob 字段的 表
create table img_table
	(img_id int auto_increment primary key,
	img_name varchar(255),
	img_data mediumblob);
 */
public class BlobTest {
	JFrame jf=new JFrame("图片管理程序");
	private static Connection conn;
	private static PreparedStatement insert;
	private static PreparedStatement query;
	private static PreparedStatement queryAll;
	
	private DefaultListModel imageModel=new DefaultListModel();
	private JList imageList=new JList(imageModel);
	private JTextField filePath=new JTextField(26);
	private JButton browserBn=new JButton("...");
	private JButton uploadBn=new JButton("上传");
	private JLabel imageLabel=new JLabel();
	
	JFileChooser chooser=new JFileChooser(".");
	ExtensionFileFilter filter=new ExtensionFileFilter();
	
	static{
		try {
			Properties prop=new Properties();
			prop.load(new FileInputStream("src/mysql.ini"));
			String driver=prop.getProperty("driver");
			String url=prop.getProperty("url");
			String user=prop.getProperty("user");
			String pass=prop.getProperty("pass");
			
			Class.forName(driver);
			conn=DriverManager.getConnection(url,user,pass);
			
			insert=conn.prepareStatement("insert into img_table(img_name,img_data) values (?,?)",Statement.RETURN_GENERATED_KEYS);
			query=conn.prepareStatement("select img_data from img_table where img_id=?");
			queryAll=conn.prepareStatement("select img_id,img_name from img_table");
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void init() throws SQLException{
		filter.addExtension("jpg");
		filter.addExtension("jpeg");
		filter.addExtension("gif");
		filter.addExtension("png");
		filter.setDescription("图片文件(*.jpg,*.jpeg,*.gif,*.png)");
		chooser.addChoosableFileFilter(filter);
		chooser.setAcceptAllFileFilterUsed(false);
		fillListModel();
		
		filePath.setEditable(false);
		//只能单选
		imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JPanel jp=new JPanel();
		jp.add(filePath);
		jp.add(browserBn);
		browserBn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				int result=chooser.showDialog(jf, "浏览图片文件上传");
				if(result==JFileChooser.APPROVE_OPTION){
					filePath.setText(chooser.getSelectedFile().getPath());
				}
			}
		});
		jp.add(uploadBn);
		uploadBn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if(filePath.getText().trim().length()>0){
					upload(filePath.getText());
					//请客文本框内容
					filePath.setText("");
				}
			}
		});
		
		JPanel left=new JPanel();
		left.setLayout(new BorderLayout());
		left.add(new JScrollPane(imageLabel),BorderLayout.CENTER);
		left.add(jp,BorderLayout.SOUTH);
		jf.add(left);
		imageList.setFixedCellWidth(160);
		jf.add(new JScrollPane(imageList),BorderLayout.EAST);
		imageList.addMouseListener(new MouseAdapter(){

			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub
				if(e.getClickCount()>=2){
					//取出选择的List
					ImageHolder cur=(ImageHolder)imageList.getSelectedValue();
					try {
						showImage(cur.getId());
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}
			
		});
		jf.setSize(620,400);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.setVisible(true);
		
	}
	
	public void fillListModel() throws SQLException{
		ResultSet rs=null;
		try {
			imageModel.clear();
			rs=queryAll.executeQuery();
			while(rs.next()){
				imageModel.addElement(new ImageHolder(rs.getInt(1),rs.getString(2)));
			}
		}finally{
			if(rs!=null)
				rs.close();
		}
		
	}
	public void upload(String fileName){
		InputStream is=null;
		try {
			String imageName=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.lastIndexOf("."));
			insert.setString(1, imageName);
			File f=new File(fileName);
			is=new FileInputStream(f);
			insert.setBinaryStream(2, is,(int)f.length());
			int affect=insert.executeUpdate();
			System.out.println(affect);
			if(affect==1)
				fillListModel();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(is!=null)
					is.close();
				
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
	}
	
	public void showImage(int id) throws SQLException{
		ResultSet rs=null;
		try {
			query.setInt(1, id);
			rs=query.executeQuery();
			if(rs.next()){
				Blob imageBlob=rs.getBlob(1);
				imageBlob.getBinaryStream();
				ImageIcon icon=new ImageIcon(imageBlob.getBytes(1l, (int)imageBlob.length()));
				imageLabel.setIcon(icon);
			}
			
		}finally{
			if(rs!=null)
				rs.close();
		}
		
	}
	
	public static void main(String[] args) throws SQLException {
		new BlobTest().init();
	}

}

//-----------------------------
package com.enhance.jdbc.blob;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.filechooser.FileFilter;

public class ExtensionFileFilter extends FileFilter {

	private String description="";
	private ArrayList<String> extensions=new ArrayList<String>();
	public  void addExtension(String extension){
		if(!extension.startsWith(".")){
			extension="."+extension;
			extensions.add(extension.toLowerCase());
		}
	}
	
	
	@Override
	public boolean accept(File f) {
		// TODO Auto-generated method stub
		if(f.isDirectory())
			return true;
		String name=f.getName().toLowerCase();
		for (String extension :extensions){
			if(name.endsWith(extension))
				return true;
		}
		return false;
	}

	public void setDescription(String aDescription){
		description=aDescription;
	}
	
	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return description;
	}

}
//----------------------------------
package com.enhance.jdbc.blob;

public class ImageHolder {

	private int id;
	private String name;
	public ImageHolder() {
		super();
		// TODO Auto-generated constructor stub
	}
	public ImageHolder(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return name;
	}
	
}


你可能感兴趣的:(rs.getBlob(1);)