用Java或Jsp向資料庫存取二進位圖片

來源:互聯網
上載者:User

當然首先您要在資料庫中先建立一個用於儲存圖片的表和相應的列,資料格式為blob

package com.lizhe;     import Java.io.*;     import java.sql.*;     public class PutImg {     public void putimg() {     try {     Class.forName("org.gjt.mm.mysql.Driver").newInstance();     String url = "JDBC:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk";     Connection conn = DriverManager.getConnection(url);     Statement stmt = conn.createStatement();     //stmt.execute("insert into imgt (id) values (5)");     stmt.close();     PreparedStatement pstmt = null;     String sql = "";     File file = new File("c:log.jpg");     InputStream photoStream = new FileInputStream(file);     //sql = " UPDATE imgt SET img = ? ";     sql = "INSERT INTO imgtable (img) VALUES (?)";     pstmt = conn.prepareStatement(sql);     pstmt.setBinaryStream(1, photoStream, (int) file.length());     pstmt.executeUpdate();     pstmt.close();     conn.close();     } catch (Exception e) {     e.printStackTrace();     }     }     public static void main(String args[]){     PutImg pi=new PutImg();     pi.putimg();     }     }  

package com.lizhe;    import Java.io.*;    import java.sql.*;    public class PutImg {    public void putimg() {    try {    Class.forName("org.gjt.mm.mysql.Driver").newInstance();    String url = "JDBC:mysql://localhost/img?user=root&password=root&useUnicode=true&characterEncoding=gbk";    Connection conn = DriverManager.getConnection(url);    Statement stmt = conn.createStatement();    //stmt.execute("insert into imgt (id) values (5)");     stmt.close();    PreparedStatement pstmt = null;    String sql = "";    File file = new File("c:log.jpg");    InputStream photoStream = new FileInputStream(file);    //sql = " UPDATE imgt SET img = ? ";     sql = "INSERT INTO imgtable (img) VALUES (?)";    pstmt = conn.prepareStatement(sql);    pstmt.setBinaryStream(1, photoStream, (int) file.length());    pstmt.executeUpdate();    pstmt.close();    conn.close();    } catch (Exception e) {    e.printStackTrace();    }    }    public static void main(String args[]){    PutImg pi=new PutImg();    pi.putimg();    }    }  

InputStream photoStream = new FileInputStream(file);  

InputStream photoStream = new FileInputStream(file);  

可以很清楚的看到我們首先把一個圖片檔案(當然也可以是別的什麼檔案)轉換成了一個二進位輸入資料流

pstmt.setBinaryStream(1, photoStream, (int) file.length());  

pstmt.setBinaryStream(1, photoStream, (int) file.length());  

這個方法建議大家去查一下API文檔,第一個參數是萬用字元位置沒的說,第二個參數是流,這和以往的string類型的參數不太一樣,我剛看到的時候也覺得豁然開朗了,但是到這裡還沒完,不同於以往的字串參數,這裡我們還需要第三個參數來設定這個流的長度,這裡也就是這個檔案的長度,匯出資料庫中的sql,一切都清楚了

  INSERT INTO `m_diy` VALUES (2,? JFIF HH?? ExifMM* b j ( 1 r 2 ?i H H Adobe Photoshop CS Windows2007:03:18 23:08:15 ? ??? ? ........等等

  其實就是將檔案先轉換成了二進位的流,然後插入到了sql語言中,向資料庫寫入了很長很長的一段sql語句

  然後我們再來寫一個app程式將這個檔案讀出來,儲存成一個圖片檔案\

package com.lizhe;     import Java.io.*;     import java.sql.*;     class GetImg {     private static final String URL = "JDBC:MySQL://localhost/img?user=root&password     =root&useUnicode=true&characterEncoding=gbk";     private Connection conn = null;     private PreparedStatement pstmt = null;     private ResultSet rs = null;     private File file = null;     public void blobRead(String outfile, int picID) throws Exception {     FileOutputStream fos = null;     InputStream is = null;     byte[] Buffer = new byte[4096];     try {     Class.forName("org.gjt.mm.mysql.Driver").newInstance();     conn = DriverManager.getConnection(URL);     pstmt = conn.prepareStatement("select img from imgt where id=?");     pstmt.setInt(1, picID); // 傳入要取的圖片的ID     rs = pstmt.executeQuery();     rs.next();     file = new File(outfile);     if (!file.exists()) {     file.createNewFile(); // 如果檔案不存在,則建立     }     fos = new FileOutputStream(file);     is = rs.getBinaryStream("img");     int size = 0;     while ((size = is.read(Buffer)) != -1) {     // System.out.println(size);     fos.write(Buffer, 0, size);     }     } catch (Exception e) {     System.out.println( e.getMessage());     } finally {     // 關閉用到的資源     fos.close();     rs.close();     pstmt.close();     conn.close();     }     }     public static void main(String[] args) {     try {     GetImg gi=new GetImg();     gi.blobRead("c:/getimgs/1.jpg", 5);     } catch (Exception e) {     System.out.println("[Main func error: ]" + e.getMessage());     }     }     }  

package com.lizhe;    import Java.io.*;    import java.sql.*;    class GetImg {    private static final String URL = "JDBC:MySQL://localhost/img?user=root&password     =root&useUnicode=true&characterEncoding=gbk";    private Connection conn = null;    private PreparedStatement pstmt = null;    private ResultSet rs = null;    private File file = null;    public void blobRead(String outfile, int picID) throws Exception {    FileOutputStream fos = null;    InputStream is = null;    byte[] Buffer = new byte[4096];    try {    Class.forName("org.gjt.mm.mysql.Driver").newInstance();    conn = DriverManager.getConnection(URL);    pstmt = conn.prepareStatement("select img from imgt where id=?");    pstmt.setInt(1, picID); // 傳入要取的圖片的ID     rs = pstmt.executeQuery();    rs.next();    file = new File(outfile);    if (!file.exists()) {    file.createNewFile(); // 如果檔案不存在,則建立     }    fos = new FileOutputStream(file);    is = rs.getBinaryStream("img");    int size = 0;    while ((size = is.read(Buffer)) != -1) {    // System.out.println(size);     fos.write(Buffer, 0, size);    }    } catch (Exception e) {    System.out.println( e.getMessage());    } finally {    // 關閉用到的資源     fos.close();    rs.close();    pstmt.close();    conn.close();    }    }    public static void main(String[] args) {    try {    GetImg gi=new GetImg();    gi.blobRead("c:/getimgs/1.jpg", 5);    } catch (Exception e) {    System.out.println("[Main func error: ]" + e.getMessage());    }    }    }  

這裡需要注意的是 

is = rs.getBinaryStream("img");  

is = rs.getBinaryStream("img");  

img是資料庫中相應的列名,其實和rs.getString()方法差不多,只不過這個方法是讀取二進位流的

  最後在帖兩個bs系統上用的檔案給大家參考

  通過Struts的action向資料庫寫入二進位圖片

/*    * Generated by MyEclipse Struts    * Template path: templates/Java/JavaClass.vtl    */     package com.lizhe.struts.action;     import java.io.File;     import java.io.FileInputStream;     import java.io.FileNotFoundException;     import java.io.IOException;     import java.io.InputStream;     import java.sql.Connection;     import java.sql.DriverManager;     import java.sql.PreparedStatement;     import java.sql.Statement;     import javax.Servlet.http.HttpServletRequest;     import javax.servlet.http.HttpServletResponse;     import org.apache.struts.action.Action;     import org.apache.struts.action.ActionForm;     import org.apache.struts.action.ActionForward;     import org.apache.struts.action.ActionMapping;     import org.apache.struts.upload.FormFile;     import com.lizhe.struts.form.UpimgForm;     /**    * MyEclipse Struts    * Creation date: 05-18-2007    *    * XDoclet definition:    * @struts.action path="/upimg" name="upimgForm" input="/userhomepage.JSP"    * @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"    */     public class UpimgAction extends Action {     /*    * Generated Methods    */     /**    * Method execute    * @param mapping    * @param form    * @param request    * @param response    * @return ActionForward    * @throws IOException    * @throws FileNotFoundException    */     public ActionForward execute(ActionMapping mapping, ActionForm form,     HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {     UpimgForm upimgForm = (UpimgForm) form;// TODO Auto-generated method stub     FormFile file=upimgForm.getFile();     InputStream is=file.getInputStream();     try {     Class.forName("org.gjt.mm.MySQL.Driver").newInstance();     String url = "JDBC:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312";     Connection conn = DriverManager.getConnection(url);     Statement stmt = conn.createStatement();     //stmt.execute("insert  into  img (id)  values  (5)");     stmt.close();     PreparedStatement pstmt = null;     String sql = "";     //File file = new File("c:log.jpg");     //InputStream photoStream = new FileInputStream(file);     //sql = "  UPDATE  imgt  SET  img  =  ?  ";     sql = "INSERT INTO img (img) VALUES (?)";     pstmt = conn.prepareStatement(sql);     pstmt.setBinaryStream(1, is, (int) file.getFileSize());     pstmt.executeUpdate();     pstmt.close();     conn.close();     } catch (Exception e) {     e.printStackTrace();     }     return mapping.findForward("userhomepage");     }     }  
/*   * Generated by MyEclipse Struts   * Template path: templates/Java/JavaClass.vtl   */    package com.lizhe.struts.action;    import java.io.File;    import java.io.FileInputStream;    import java.io.FileNotFoundException;    import java.io.IOException;    import java.io.InputStream;    import java.sql.Connection;    import java.sql.DriverManager;    import java.sql.PreparedStatement;    import java.sql.Statement;    import javax.Servlet.http.HttpServletRequest;    import javax.servlet.http.HttpServletResponse;    import org.apache.struts.action.Action;    import org.apache.struts.action.ActionForm;    import org.apache.struts.action.ActionForward;    import org.apache.struts.action.ActionMapping;    import org.apache.struts.upload.FormFile;    import com.lizhe.struts.form.UpimgForm;    /**   * MyEclipse Struts   * Creation date: 05-18-2007   *   * XDoclet definition:   * @struts.action path="/upimg" name="upimgForm" input="/userhomepage.JSP"   * @struts.action-forward name="userhome" path="/userhomepage.jsp" redirect="true" contextRelative="true"   */    public class UpimgAction extends Action {    /*   * Generated Methods   */    /**   * Method execute   * @param mapping   * @param form   * @param request   * @param response   * @return ActionForward   * @throws IOException   * @throws FileNotFoundException   */    public ActionForward execute(ActionMapping mapping, ActionForm form,    HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {    UpimgForm upimgForm = (UpimgForm) form;// TODO Auto-generated method stub     FormFile file=upimgForm.getFile();    InputStream is=file.getInputStream();    try {    Class.forName("org.gjt.mm.MySQL.Driver").newInstance();    String url = "JDBC:mysql://localhost/blog?user=root&password=root&useUnicode=true&characterEncoding=gb2312";    Connection conn = DriverManager.getConnection(url);    Statement stmt = conn.createStatement();    //stmt.execute("insert  into  img (id)  values  (5)");     stmt.close();    PreparedStatement pstmt = null;    String sql = "";    //File file = new File("c:log.jpg");     //InputStream photoStream = new FileInputStream(file);     //sql = "  UPDATE  imgt  SET  img  =  ?  ";     sql = "INSERT INTO img (img) VALUES (?)";    pstmt = conn.prepareStatement(sql);    pstmt.setBinaryStream(1, is, (int) file.getFileSize());    pstmt.executeUpdate();    pstmt.close();    conn.close();    } catch (Exception e) {    e.printStackTrace();    }    return mapping.findForward("userhomepage");    }    }  

和app的方式幾乎是一樣的

  第二個檔案是通過jsp將資料庫中的圖片顯示在頁面上

  這個有些不同

< %@  page  contentType="text/html;charset=gb2312"%>     < %@  page  import="java.sql.*"  %>     < %@  page  import="java.util.*"%>     < %@  page  import="java.text.*"%>     < %@  page  import="java.io.*"%>     < %@  page  import="java.awt.*"%>     < html>     < body>     < %     Class.forName("org.gjt.mm.mysql.Driver").newInstance();     String url="jdbc:mysql://localhost/img?user=root&password=root";     Connection  con  =  DriverManager.getConnection(url);     String  sql  =  "select  *  from imgt where id=5";     Statement stmt = con.createStatement();     ResultSet rs = stmt.executeQuery(sql);     if(rs.next()) {     InputStream in = rs.getBinaryStream("img");     ServletOutputStream op = response.getOutputStream();     int len;     byte[] buf=new byte[1024];     while((len= in.read(buf))!=-1) {     op.write(buf, 0, len);     }     op.close();     in.close();     }     rs.close();     stmt.close();     con.close();     %>     < /body>     < /html>  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.