本文将阐述怎么使用commons-fileupload将图片上传至mysql数据库,并利用java servlet将其在浏览器中显示
出来。
前提条件:
正确安装了mysql,tomcat,并下载了commons-fileupload-1.0.jar。
1,前台页面
---test_upload.htm---
<html>
<head>
<title>
上传测试
</title>
<body>
<form action="upload.jsp" enctype="multipart/form-data" method="post">
your name:
<br>
<input type="text" name="name">
<br>
file to process:
<input type="file" name="userfile">
<br>
<input type="submit">
</form>
</body>
</html>
2,上传的后台处理页面
---upload.jsp---
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="org.apachemons.fileupload.*" %>
<%@ page import="del.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 = ((()).getString();
FileItem fi = (();
String fileName = fi.getName();
//System.out.println(fileName);
fileName = place(':','_');
fileName = place('\\','_');
//System.out.println(fileName);
//File savedFile = new File("d:/java/upload/",fileName);
//fi.write(savedFile);
InputStream InputStream();
DbManipulate dm=new DbManipulate();
Long long_size=new Size());
int size=long_size.intValue();
PreparedStatement ps=dm.DbUpdate("insert into photo(image,description) values(?,?)");
ps.setBinaryStream(1,fis,size);
ps.setString(2,fileName);
String sql="select id from photo order by id desc limit 1";
PreparedStatement ps2=dm.DbQuery(sql);
ResultSet uteQuery();
int index=0;
())
{
Int(1);
}
//ps.close();
//fis.chose();
%>
<%=name%>  <a href="(-1)">go on</a>
<br>
<iframe height="600" width="800" src=photoview?id=<%=index%> scrolling=true>
3,显示图片的servlet
---BlobServlet.java----
package com.cf.photo;
import java.io.*;
import java.sql.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
//import org.apachemons.logging.Log;
//import org.apachemons.logging.LogFactory;
import del.*;
public class BlobServlet extends HttpServlet{
//private static Log log = Log(BlobServlet.class);
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
ServletOutputStream OutputStream();
int id=Integer.Parameter("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);
uteQuery();
()){
Blob(1);
}
Bytes(1,(int)(blob.length()));
}catch(SQLException e){}
return bytes;
}
}
4,存储图片的表定义:
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,应用程序的目录结构
%catalina_home%\webapps\demo
------test_upload.htm
------upload.jsp
------WEB-INF
|----l
|-----l
|-----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,l文件内容
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"java.sun/j2ee/dtds/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>photoview</servlet-name>
<servlet-class>com.cf.photo.BlobServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>photoview</servlet-name>
<url-pattern>/photoview/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>default.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>test.jsp</welcome-file>
</welcome-file-list>
</web-app>
7,ant的buildfile内容
------l------
<project name="buildweb" default="build" basedir=".">
<property name="src" location="src"/>
<property name="lib" location="lib"/>
<property name="build" location="classes"/>
<target name="build">
<mkdir dir="${build}" />
<javac srcdir="${src}" destdir="${build}">
<include name="**/*.java" />
</javac>
</target>
<target name="create-jars" depends="build">
<jar destfile="${lib}/myexam.jar" basedir="${build}"/>
</target>
<target name="clean" depends="create-jars">
<delete dir="${build}"/>
</target>
</project>
8,DbConst.java
package del;
public interface DbConst{
public final static String JDBC_DRIVER="sql.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 del;
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)
{
javaservlet和jsp的比较
}
finally {
con=null;
}
}
}
public void setCon(Connection c){
<=c;
}
public Connection getCon() throws SQLException{
if(isConnected()) throw new SQLException("Already 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");
}
Connection(databaseURL,dbUsername,dbPassword);
return con;
}
}
10,DbManipulate.java
package del;
import java.sql.*;
public class DbManipulate{
private Connection con=null;
private PreparedStatement pstmt=null;
public PreparedStatement DbQuery(String sql)throws SQLException{
DbConnection newcon=new DbConnection();
Con();
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();
pstmt=con.prepareStatement(sql);
return pstmt;
}
public void DbClose(){
if(pstmt!=null){
pstmt=null;
}
}
}
11,转到该web application的WEB-INF下,在命令行中执行ant,以编译源文件,然后打开tomcat服务器,
在浏览器中打开地址:localhost:8080/demo/tes
t_upload.htm,试着去上传一张jpg的图片,看看行不行。
12,欢迎大家提出宝贵意见,请联系我:
email:cf0124@163
msn:cf_asp_master@yahoo

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。