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

来源:互联网 发布:mac nestopia手柄设置 编辑:程序博客网 时间:2024/04/29 01:01
本文将阐述怎么使用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
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 十天婴儿不大便怎么办 宝宝断奶不喝牛奶怎么办 宝宝喝羊奶大便干燥怎么办 4个月宝宝睡眠少怎么办 8个月婴儿不吃奶粉怎么办 满月的宝宝黄疸高怎么办 刚满月的宝宝黄疸高怎么办 换奶粉孩子不喝怎么办 宝宝整夜哭闹不睡觉怎么办 满月宝宝整夜不睡觉怎么办 6个半月宝宝一喂粥就哭怎么办 宝宝敷鸡蛋白过敏怎么办 七个月宝宝不吃米糊怎么办 涨奶引起的发烧怎么办 8个月宝宝积食怎么办 宝宝吃奶一会就睡了怎么办 宝宝喝凉酸奶拉肚子怎么办 宝宝戒奶不吃奶粉怎么办 三个月大婴儿不吃奶粉怎么办 三个月大的婴儿不吃奶粉怎么办 40天宝宝肚脐凸怎么办 6个月婴儿消化不好怎么办 2个月婴儿消化不好怎么办 10月婴儿不吃饭怎么办 9个月宝宝不吃饭怎么办 十个多月的宝宝便秘怎么办 十个多月宝宝便秘怎么办 8个月宝宝过敏怎么办 宝宝二十个月便秘怎么办 7个月宝宝便秘拉不出怎么办 二十六个月宝宝便秘怎么办 八个月宝宝吃鸡蛋过敏怎么办 8个月宝宝 吃盐怎么办 40多天婴儿拉肚怎么办 刚出生婴儿拉肚怎么办 20多天婴儿拉肚怎么办 米汤煮的太稠了怎么办 两岁宝宝不吃蔬菜怎么办 两岁宝宝不爱吃蔬菜怎么办 四个月宝宝头有点歪怎么办 宝宝吃过了还闹怎么办