Of course, you must first create a table and corresponding columns for saving images in the database. The data format is 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);
We can clearly see that we first convert an image file (or another file, of course) into a binary input stream.
pstmt.setBinaryStream(1, photoStream, (int) file.length());
pstmt.setBinaryStream(1, photoStream, (int) file.length());
For this method, we recommend that you check the API documentation. The first parameter is the wildcard parameter, and the second parameter is the stream. This is not the same as the previous string parameter, when I first saw it, I also felt very open, but it was not complete yet. Unlike the previous string parameters, here we need a third parameter to set the length of the stream, this is the length of the file. Everything is clear when exporting SQL statements from the database.
Insert into'm _ DIY 'values (2 ,? Jfif Hh ?? Exifmm * B J (1 R 2? I h Adobe Photoshop CS windows2007: 03: 18 23:08:15? ??? ? ... And so on
In fact, the file is first converted into a binary stream, and then inserted into the SQL language, writing a long SQL statement to the database
Then we will write an app to read the file and store it as an image file \
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 = 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); // input the ID rs = pstmt.exe cutequery (); RS. next (); file = new file (OUTFILE); If (! File. exists () {file. createnewfile (); // if the file does not exist, create} 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 {// close the resource Fos used. 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 = 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); // input the ID rs = pstmt.exe cutequery (); RS. next (); file = new file (OUTFILE); If (! File. exists () {file. createnewfile (); // if the file does not exist, create} 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 {// close the resource Fos used. 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 ());}}}
Note that
is = rs.getBinaryStream("img");
is = rs.getBinaryStream("img");
IMG is the corresponding column name in the database. In fact, it is similar to the RS. getstring () method, but this method reads binary streams.
Finally, I will post the files used by the BS system for your reference.
Write binary images to the database through 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"); } }
The method is almost the same as that of the app.
The second file is to display images in the database on the page through JSP.
This is somewhat different.
< %@ 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>