用Java或Jsp向数据库存取二进制图片
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
?前幾天突然看到學(xué)校音樂站上的圖片原來是存儲在數(shù)據(jù)庫上的,是二進(jìn)制而不是使用路徑保存的,在網(wǎng)上招了找發(fā)現(xiàn)大多介紹的都是hph方式,在這里做個(gè)總結(jié),首先要存儲二進(jìn)制文件在數(shù)據(jù)庫中要搞清楚下面幾個(gè)內(nèi)容:1 MySQL存儲大容量的二進(jìn)制文件的格式是blob,其實(shí)除了圖片還可以存別的
2 要向數(shù)據(jù)庫存儲二進(jìn)制的文件一定要把要存儲的數(shù)據(jù)轉(zhuǎn)換成二進(jìn)制流
廢話就不多說了,大家看看代碼很容易明白,先來看一個(gè)app程序,當(dāng)然首先您要在數(shù)據(jù)庫中先建立一個(gè)用于保存圖片的表和相應(yīng)的列,數(shù)據(jù)格式為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(); } } |
InputStream photoStream = new FileInputStream(file);
可以很清楚的看到我們首先把一個(gè)圖片文件(當(dāng)然也可以是別的什么文件)轉(zhuǎn)換成了一個(gè)二進(jìn)制輸入流
pstmt.setBinaryStream(1,?photoStream,?(int)?file.length()); |
這個(gè)方法建議大家去查一下API文檔,第一個(gè)參數(shù)是通配符位置沒的說,第二個(gè)參數(shù)是流,這和以往的string類型的參數(shù)不太一樣,我剛看到的時(shí)候也覺得豁然開朗了,但是到這里還沒完,不同于以往的字符串參數(shù),這里我們還需要第三個(gè)參數(shù)來設(shè)置這個(gè)流的長度,這里也就是這個(gè)文件的長度,導(dǎo)出數(shù)據(jù)庫中的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 ? ??? ? ........等等
其實(shí)就是將文件先轉(zhuǎn)換成了二進(jìn)制的流,然后插入到了sql語言中,向數(shù)據(jù)庫寫入了很長很長的一段sql語句
然后我們再來寫一個(gè)app程序?qū)⑦@個(gè)文件讀出來,存儲成一個(gè)圖片文件
? 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();?//?如果文件不存在,則創(chuàng)建 } 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?{ //?關(guān)閉用到的資源 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"); |
img是數(shù)據(jù)庫中相應(yīng)的列名,其實(shí)和rs.getString()方法差不多,只不過這個(gè)方法是讀取二進(jìn)制流的
最后在帖兩個(gè)bs系統(tǒng)上用的文件給大家參考
通過Struts的action向數(shù)據(jù)庫寫入二進(jìn)制圖片
? /* *?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的方式幾乎是一樣的
第二個(gè)文件是通過jsp將數(shù)據(jù)庫中的圖片顯示在頁面上
這個(gè)有些不同
?? <?%@ ?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> |
轉(zhuǎn)載于:https://my.oschina.net/u/1044955/blog/277109
總結(jié)
以上是生活随笔為你收集整理的用Java或Jsp向数据库存取二进制图片的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 08 事件处理
- 下一篇: MariaDB10和MySQL5.6社区