1. 程式人生 > >java 在MySQL中儲存檔案,讀取檔案(包括圖片,word文件,excel表格,ppt,zip檔案等)

java 在MySQL中儲存檔案,讀取檔案(包括圖片,word文件,excel表格,ppt,zip檔案等)

  在設計到資料庫的開發中,難免要將圖片或文件檔案(如word)插入到資料庫中的情況。一般來說,我們可以通過插入檔案相應的儲存路徑,而不是檔案本身,來避免直接向資料庫裡插入的麻煩。但有些時候,直接向MySQL中插入檔案,更加安全,而且更加容易管理。
  首先,先要在資料庫中建表。我在名為test的資料庫下建立了一個叫pic的表。該表包括3列,id, caption和img。其中id是主鍵,caption是對圖片的表述,img是影象檔案本身。建表的SQL語句如下:
DROP TABLE IF EXISTS `test`.`pic`;
CREATE TABLE `test`.`pic` (
 `id` int(11) NOT NULL auto_increment,
 `caption` varchar(45) NOT NULL default '',
 `img` longblob NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  其次,在java中對檔案(如圖片,word文件等)的處理,其中包括把檔案儲存到資料庫和從資料庫中讀取檔案。(注:storeImg()和readImg()是可以處理任意檔案型別的,不僅僅是圖片)
</pre><pre name="code" class="sql">  在資料庫裡儲存檔案以及從資料庫讀取檔案的完整程式碼如下:
<pre name="code" class="java">import java.io.*;
import java.sql.*;
public class StoreFile {
	
    private String dbDriver;
    private String dbURL;
    private String dbUser;
    private String dbPassword;
    private Connection con;
    private PreparedStatement ps;  
    /**
   	 * 建構函式,初始化資料庫的連線
   	 * 
   	 */
    public StoreFile() {
        dbDriver = "com.mysql.jdbc.Driver";
        dbURL = "jdbc:mysql://localhost:3306/test";
        dbUser = "root";
        dbPassword = "justdoit";
        initDB();
    }  
    public StoreFile(String strDriver, String strURL,
            String strUser, String strPwd) {
        dbDriver = strDriver;
        dbURL = strURL;
        dbUser = strUser;
        dbPassword = strPwd;
        initDB();
    }
 
    public void initDB() {
        try {
            // Load Driver
            Class.forName(dbDriver).newInstance();
            // Get connection
            con = DriverManager.getConnection(dbURL,
                    dbUser, dbPassword);           
        } catch(ClassNotFoundException e) {
            System.out.println(e.getMessage());
        } catch(SQLException ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
 
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    /**
	 * 將指定路徑的檔案(比如:圖片,word文件等)儲存到資料庫
	 * @param strFile 要存放到資料庫的檔案路徑,如D:\\a.jpg
	 */
    public void storeImg(String strFile) throws Exception {
            int id = 0;
            File file = new File(strFile);
            FileInputStream fis = new FileInputStream(file);           
            try {              
                ps = con.prepareStatement("insert "
                        + "into PIC values (?,?,?)");
                ps.setInt(1, id);
                ps.setString(2, file.getName());
                ps.setBinaryStream(3, fis, (int) file.length());
                ps.executeUpdate();  
                System.out.println("file insert success ");
            } catch (SQLException e) {
                System.out.println("SQLException: "
                        + e.getMessage());
                System.out.println("SQLState: "
                        + e.getSQLState());
                System.out.println("VendorError: "
                        + e.getErrorCode());
                e.printStackTrace();
            } finally {            
                ps.close();
                fis.close();
                con.close();
            }       
    }
    /**
	 * 將儲存在資料庫中的檔案(比如:圖片,word文件等)讀取到指定路徑
	 * @param path  從資料庫裡讀取出來的檔案存放路徑 如D:\\a.jpg
	 * @param id    資料庫裡記錄的id
	 */
    public void readImg(String path, int id) throws Exception{
    	initDB();   //建立與資料庫的連線
    	byte[] buffer = new byte[4096];
    	FileOutputStream outputImage = null;
    	InputStream is = null;
    	try {
    	    ps = con.prepareStatement("select img from pic where id =?");
    	    ps.setInt(1, id);
    	    ResultSet rs = ps.executeQuery();
    	    rs.next();
    	    File file = new File(path);
    	    if (!file.exists()) {
    	      file.createNewFile();   	    
    	    }
    	    outputImage = new FileOutputStream(file);    	       	    	
    	    Blob blob = rs.getBlob("img");   //img為資料庫存放圖片欄位名稱
    	    is = blob.getBinaryStream();    	   
    	    int size = 0; 	   
    	    while ((size = is.read(buffer)) != -1) {  	     
    	    	outputImage.write(buffer, 0, size);   	     
    	    }
    	    System.out.println("file read success ");
    	} catch (Exception e) {
    		   e.printStackTrace();
    	   } finally {
    	     is.close();
    	     outputImage.close();
    	     ps.close();
    	     con.close();
    	   }
    	}
   
    public static void main(String[] args) throws Exception {
        StoreFile sp = new StoreFile();
        String imgPath="C:\\Users\\Administrator\\Pictures\\img12.jpg";
        //String wordPath="d:\\測試文件.docx";
        sp.storeImg(imgPath);
        //sp.storeImg(wordPath);
        //sp.readImg("D://資料庫.jpg", 1);  //這裡的1為要傳入的引數:讀取檔案的id
        //sp.readImg("D://資料庫.docx", 8);
    }
}