?? blobtest.java
字號:
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Properties;
import java.util.ArrayList;
import java.io.*;
import javax.swing.filechooser.FileFilter;
/**
* Description:
* <br/>Copyright (C), 2005-2008, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class BlobTest
{
JFrame jf = new JFrame("圖片管理程序");
private static Connection conn;
private static PreparedStatement insert;
private static PreparedStatement query;
private static PreparedStatement queryAll;
//定義一個DefaultListModel對象
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();
//以當(dāng)前路徑創(chuàng)建文件選擇器
JFileChooser chooser = new JFileChooser(".");
//創(chuàng)建文件過濾器
ExtensionFileFilter filter = new ExtensionFileFilter();
static
{
try
{
Properties props = new Properties();
props.load(new FileInputStream("mysql.ini"));
String driver = props.getProperty("driver");
String url = props.getProperty("url");
String user = props.getProperty("user");
String pass = props.getProperty("pass");
Class.forName(driver);
//獲取數(shù)據(jù)庫連接
conn = DriverManager.getConnection(url , user , pass);
//創(chuàng)建執(zhí)行插入的PreparedStatement對象,該對象執(zhí)行插入后可以返回自動生成的主鍵
insert = conn.prepareStatement("insert into img_table values(null,?,?)"
, Statement.RETURN_GENERATED_KEYS);
//創(chuàng)建兩個PreparedStatement對象,用于查詢指定圖片,查詢所有圖片
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()
{
public void actionPerformed(ActionEvent event)
{
//顯示文件對話框
int result = chooser.showDialog(jf , "瀏覽圖片文件上傳");
//如果用戶選擇了APPROVE(贊同)按鈕,即打開,保存及其等效按鈕
if(result == JFileChooser.APPROVE_OPTION)
{
filePath.setText(chooser.getSelectedFile().getPath());
}
}
});
jp.add(uploadBn);
uploadBn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent avt)
{
//如果上傳文件的文本框有內(nèi)容
if (filePath.getText().trim().length() > 0)
{
//將指定文件保存到數(shù)據(jù)庫
upload(filePath.getText());
//清空文本框內(nèi)容
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()
{
public void mouseClicked(MouseEvent e)
{
//如果鼠標(biāo)雙擊
if (e.getClickCount() >= 2)
{
//取出選中的List項
ImageHolder cur = (ImageHolder)imageList.getSelectedValue();
try
{
//顯示選中項對應(yīng)的Image
showImage(cur.getId());
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
}
}
});
jf.setSize(620, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
//----------查找img_table填充ListModel----------
public void fillListModel()throws SQLException
{
ResultSet rs = null;
try
{
//先清除所有元素
imageModel.clear();
//執(zhí)行查詢
rs = queryAll.executeQuery();
//把查詢的全部記錄添加到ListModel中
while (rs.next())
{
imageModel.addElement(new ImageHolder(rs.getInt(1),
rs.getString(2)));
}
}
finally
{
if (rs != null)
{
rs.close();
}
}
}
//---------將指定圖片放入數(shù)據(jù)庫---------
public void upload(String fileName)
{
InputStream is = null;
try
{
//截取文件名
String imageName = fileName.substring(
fileName.lastIndexOf('\\') + 1 , fileName.lastIndexOf('.'));
//設(shè)置圖片名參數(shù)
insert.setString(1, imageName);
File f = new File(fileName);
is = new FileInputStream(f);
//設(shè)置二進制流參數(shù)
insert.setBinaryStream(2, is , (int)f.length());
int affect = insert.executeUpdate();
if (affect == 1)
{
//重新更新ListModel,將會讓JList顯示最新的圖片列表
fillListModel();
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if (is != null)
{
is.close();
}
}
catch (Exception e)
{
}
}
}
//---------根據(jù)圖片ID來顯示圖片----------
public void showImage(int id)throws SQLException
{
ResultSet rs = null;
try
{
//設(shè)置參數(shù)
query.setInt(1, id);
//執(zhí)行查詢
rs = query.executeQuery();
if (rs.next())
{
//取出Blob列
Blob imgBlob = rs.getBlob(1);
//取出Blob列里的數(shù)據(jù)
ImageIcon icon = new ImageIcon(imgBlob.getBytes(1L , (int)imgBlob.length()));
imageLabel.setIcon(icon);
}
}
finally
{
if (rs != null)
{
rs.close();
}
}
}
public static void main(String[] args)throws SQLException
{
new BlobTest().init();
}
}
//創(chuàng)建FileFilter的子類,用以實現(xiàn)文件過濾功能
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());
}
}
//用于設(shè)置該文件過濾器的描述文本
public void setDescription(String aDescription)
{
description = aDescription;
}
//繼承FileFilter類必須實現(xiàn)的抽象方法,返回該文件過濾器的描述文本
public String getDescription()
{
return description;
}
//繼承FileFilter類必須實現(xiàn)的抽象方法,判斷該文件過濾器是否接受該文件
public boolean accept(File f)
{
//如果該文件是路徑,接受該文件
if (f.isDirectory()) return true;
//將文件名轉(zhuǎn)為小寫(全部轉(zhuǎn)為小寫后比較,用于忽略文件名大小寫)
String name = f.getName().toLowerCase();
//遍歷所有可接受的擴展名,如果擴展名相同,該文件就可接受。
for (String extension : extensions)
{
if (name.endsWith(extension))
{
return true;
}
}
return false;
}
}
//創(chuàng)建一個ImageHolder類,用于封裝圖片名、圖片ID
class ImageHolder
{
//封裝圖片的ID
private int id;
//封裝圖片的圖片名字
private String name;
public ImageHolder()
{
}
public ImageHolder(int id , String name)
{
this.id = id;
this.name = name;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return this.id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
//重寫toString方法,返回圖片名
public String toString()
{
return name;
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -