This article will explain how to use Commons-fileUPload to upload images to the MySQL database and use the Java servlet to display it in your browser.
come out.
Prerequisites:
MYSQL, Tomcat was installed correctly, and Commons-fileUpload-1.0.jar was downloaded.
1, front page
--- Test_UPLOAD.HTM ---
2. Upload background processing page
--- UPLOAD.JSP ---
<% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Page Import = "Java.io. *"%> <% @ page import = "java.sql. *"%>
<% @ page import = "java.util. *"%> <% @ page import = "org.apache.commons.fileUpload. *"%> <% @ page import = "com.cf.model.dbmanipulate"% > <% DiskFileUpload upload = new DiskFileUpload (); upload.setSizeThreshold (4096); upload.setRepositoryPath ( "d: / java /"); upload.setSizeMax (10000000); List fileItems = upload.parseRequest (request); Iterator i = fileItems.ITerator (); string name = ((fileItem) i.next ()). getString (); fileItem FI = (fileItem) i.next (); string filename = fi.getname (); // system. Out.println (filename); filename = filename.replace (':', '_'); filename = filename.Replace ('//', '_'); //system.out.println (FileName); / / File savedfile = new file ("D: / java / upload /", filename); //fi.write( //fi.write(); inputStream FIS = fi.getinputStream (); dbmanipulate DM = New dbmanipulate (); long long_size = new Long (FI.GETSIZE ()); int size = long_size.intValue (); preparedStatement PS = DM.DBUPDATE ("IMAGE, DESCRIPTIO n) VALUES (?,?) "); ps.setbinaryStream (1, fis, size); ps.setstring (2, filename); ps.executeUpdate (); string sql =" select id from photo order by id desc limit 1 "; prepaaredStatement PS2 = DM.DBQUERY (SQL); ResultSet RS = ps2.executeQuery (); int index = 0; if (rs.next ()) {index = rs.getint (1);} // ps. Close (); //fis.chose ();%> <% = name%> Go on
Scrolling = true> 3, servlet displaying the picture
--- blobservlet.java ------
Package com.cf.photo;
Import java.io. *; import java.sql. *; import javax.sql. *; import javax.servlet. *; import javax.servlet.http. *; // import org.apache.commons.logging.log; // Import org.apache.commons.logging.logfactory;
Import com.cf.model. *;
Public class blobservlet extends httpservlet {// private static log log = logfactory.getlog (blobservlet.class);
Protected void doget (httpservletRequest request, httpservletResponse response) throws servletexception, ioException {
ServletOutputStream out = response.getOutputStream (); int id = Integer.parseInt (request.getParameter ( "id")); response.setContentType ( "image / jpeg"); out.write (getBlob (id)); out.flush (); Out.close (); PUBLIC BYTE [] getBlob (int photoid) {string SQL = "SELECT image from photo where id =?"; //Log.info(SQL); blob blob = null; Byte [ ] bytes = null; // String description = ""; PreparedStatement pstmt = null; ResultSet rs = null; DbManipulate mydb = new DbManipulate (); try {pstmt = mydb.DbQuery (sql); pstmt.setInt (1, photoid) Rs = pstmt.executeQuery (); while (rs.next ()) {blob = rs.getblob (1);} BYTES = blob.getbytes (1, (int)));} catch (SQLException E) {} Return Bytes;}}
4. Store the table definition of the image:
Create Database Web_exam;
USE web_exam;
Create Table Photo
ID INT NOT NULL AUTO_INCREMENT Primary Key,
Image Mediumblob NOT NULL,
Description varchar (100) NULL
);
5. Directory structure of the app
% Catalina_Home% / WebApps / Demo
------ Test_UPLOAD.HTM
------ UPLOAD.JSP
------ WEB-INF
| ---- Web.xml
| ----- Build.xml
| ----- LIB
| ------- MySQL-Connector-Java-3.0.16-Ga-bin.jar
| ------- Commons-fileupload-1.0.jar
| ---- SRC | ---- COM
| ----- CF
| ----- Photo
| ----- blobservlet.java
| ----- Model
| ---- DBConnection.java
| ---- DBCONST.JAVA
| ---- DBManipulate.java
6, web.xml file content
XML Version = "1.0"?>
photoview servlet-name> com.cf.photo.blobservlet servlet-class> servlet> PhotoView servlet-name> /photoView / * url-pattern> servlet-maping>
default.jsp welcome-file> index.jsp welcome-file> test.jsp welcome-file> < / Welcome-file-list>
web-app>
7, Ant's buildfile content
------ Build.xml ------
< INCLUDE NAME = "** / *. java" /> javac> target> target> target> project>
8, dbconst.java
Package com.cf.model;
public interface DbConst {public final static String JDBC_DRIVER = "com.mysql.jdbc.Driver"; public final static String JDBC_URL = "jdbc: mysql: // localhost: 3306 / web_exam?" "useUnicode = true & characterEncoding = GB2312"; public Final static string JDBC_USER = "root"; public final static string jdbc_pass = "chenfu";} 9, dbconnection.java
Package com.cf.model; import java.sql. *; public class dbconnection implements dbconst {
private String jdbcDriver = JDBC_DRIVER; private String databaseURL = JDBC_URL; private String dbUsername = JDBC_USER; private String dbPassword = JDBC_PASS; private Connection con = null; public String getJdbcDriver () {return this.jdbcDriver;} public void setJdbcDriver (String d) { this.jdbcDriver = d;} public String getDatabaseURL () {return this.databaseURL;} public void setDatabaseURL (String url) {this.databaseURL = url;} public String getDbUsername () {return this.dbUsername;} public void setDbUsername ( String u) {this.dbUsername = u;} public String getDbPassword () {return this.dbPassword;} public void setDbPassword (String p) {this.dbPassword = p;}! public boolean isConnected () {return (con = null } Public void disconnected () {if (con! = Null) {Try {con.close ();} catch (sqlexception ignore) {} finally {con = NULL;}}} public void setcon (connection c) { THIS.CON = C;} public connection getcon () THROWS SQLEXCEPTION {IF (iSconnected ()) throw new sqlexception ("alreadyady connected "); if (jdbcDriver == null) throw new SQLException (" No jdbcDriver property "); if (databaseURL == null) throw new SQLException (" No jdbcURL property "); try {Class.forName (jdbcDriver); / /log.info(jdbcDriver);} catch (ClassNotFoundException e) {throw new SQLException (jdbcDriver "class could not loaded");} con = DriverManager.getConnection (databaseURL, dbUsername, dbPassword); return con;}}
10, dbmanipulate.java
Package com.cf.model; import java.sql. *; public class dbmanipulate {private connection con = null; private preparedState pstmt = null;
public PreparedStatement DbQuery (String sql) throws SQLException {DbConnection newcon = new DbConnection (); con = newcon.getCon (); pstmt = con.prepareStatement (sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); //log.info(sql ); return pstmt;} public PreparedStatement DbUpdate (String sql) throws SQLException {DbConnection newcon = new DbConnection (); con = newcon.getCon (); pstmt = con.prepareStatement (sql); return pstmt;} public void dbClose () {If (pStmt! = Null;}}} 11, go to the web-inferry of the web application, execute Ant in the command line to compile the source file, then open the Tomcat server,
Open the address in the browser: http: // localhost: 8080 / demo / test_upload.htm, try to go upload a JPG picture, see if it is not possible.
12. Welcome everyone to make valuable comments, please contact me:
Email: cf0124@163.com
MSN: CF_ASP_MASTER@yahoo.com.cn