java中图片上传并在jsp页面显示

本文将阐述怎么使用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.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(savedFile);
InputStream fis=fi.getInputStream();
DbManipulate dm=new DbManipulate();
Long long_size=new Long(fi.getSize());
int size=long_size.intValue();
PreparedStatement ps=dm.DbUpdate("insert into photo(image,description) values(?,?)");
ps.setBinaryStream(1,fis,size);
ps.setString(2,fileName);
ps.executeUpdate();
String sql="select id from photo order by id desc limit 1";
PreparedStatement ps2=dm.DbQuery(sql);
ResultSet rs=ps2.executeQuery();
int index=0;
if(rs.next())
{
index=rs.getInt(1);
}
//ps.close();
//fis.chose();
%>
<%=name%> <a href="javascript:history.go(-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.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)(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

|----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文件内容

<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/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内容

------build.xml------

<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 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("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");
}
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 PreparedStatement 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){
pstmt=null;
}
}
}

11,转到该web application的WEB-INF下,在命令行中执行ant,以编译源文件,然后打开tomcat服务器,

在浏览器中打开地址:http://localhost:8080/demo/test_upload.htm,试着去上传一张jpg的图片,看看行不行。

12,欢迎大家提出宝贵意见,请联系我:

email:luckyboyguo@126.com

QQ:263235040
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值