Struts2上传图片到Mysql数据库中,以及显示到页面
2010-10-14 16:30 java ee spring 阅读(283) 评论(0) 编辑 收藏 举报数据库的创建:
数据库名叫:csdn
表名:savepicture
DROP TABLE IF EXISTS `savepicture`;
CREATE TABLE `savepicture` (
`id` int(10) NOT NULL auto_increment,
`picture` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
好动手创建工程啦:
其实非常简单,一看就明白。把需要的包该导的都导了就行了。
接着我们创建上传页面:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>File Upload</title>
<link href="<%=request.getContextPath()%>/css/fileupload.css"
rel="stylesheet" type="text/css">
</head>
<body bgcolor="#cccccc">
<div style="padding-top: 30px; padding-left: 30px">
<fieldset
style="width: 600px; border-color: #000000; padding-left: 10px">
<legend>
<font size="-1" color="#000000"><b>上传图片</b> </font>
</legend>
<div class="ErrorDiv">
<s:fielderror/>
<s:actionerror/>
</div>
<s:form action="fileUpload.action" method="post" theme="simple"
enctype="multipart/form-data">
<table border="1" width="500px">
<tr>
<td class="tableTDCenter">
图片路径:
</td>
<td class="tableTDCenter">
<s:file name="file" cssClass="fileInput"/>
</td>
</tr>
<tr>
<td class="tableTDCenter" colspan="2">
<s:submit value="提交" cssClass="button"></s:submit>
</td>
</tr>
</table>
</s:form>
</fieldset>
</div>
</body>
</html>
很简单,就是个上传框和按钮,别的没有了。至于一些css就是稍微的装饰装饰,一会也在下面写上!
上传成功的画面:
<%@ page language="java" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Image List</title> <link href="<%=request.getContextPath()%>/css/fileupload.css" rel="stylesheet" type="text/css"> </head> <body> <s:iterator value="#list" id="picture"> <div class="divfloat"> <img src='outPicture.action?id=<s:property value ="#picture.id"/>'> </div> </s:iterator> </body> </html>
下面我们看看struts2的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources"
value="messageResource" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<package name="default" extends="struts-default">
<!--上传-->
<action name="fileUpload"
class="org.csdn.action.FileUploadAction">
<interceptor-ref name ="defaultStack" />
<interceptor-ref name ="fileUpload">
<param name ="allowedTypes">
image/bmp,image/png,image/gif,image/jpg
</param>
<param name="maximumSize">404800</param>
</interceptor-ref>
<result name="success">/uploadSuccess.jsp</result>
<result name="input">/fileUpload.jsp</result>
</action>
<!--输出显示-->
<action name="outPicture"
class="org.csdn.action.OutPictureAction">
<result name="input">/uploadSuccess.jsp</result>
</action>
</package>
</struts>
至于里面的东西是什么,大家肯定根据名字一看就知道了。
上面我引用了messageResource资源文件,为了显示错误消息。比如上传类型不正确,超过大小,以及上传失败。
下面就是资源文件中的内容。
struts.messages.error.content.type.not.allowed=The file you uploaded is not a image
struts.messages.error.file.too.large=this picutre is too large
fileupload.fail=file upload is fail
如果没有重新定义上面两个key的话,显示的会是struts2默认的错误消息,很是难看,也乱起八糟的。所以我重新定义了。
接着我们就开始写上传和输出图片的action,以及相关的类信息
上传的action:
import java.io.File;
import java.util.List;
import org.csdn.service.FileUploadService;
import org.csdn.vo.Picture;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author closewubq
*/
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
/**
* 上传文件
*/
@Override
public String execute() {
FileUploadService fuservice=new FileUploadService();
if(fuservice.fileUpload(file)){
List<Picture> list=fuservice.findAll();
ActionContext cxt=ActionContext.getContext();
cxt.put("list",list);
return SUCCESS;
}else{
super.addActionError(this.getText("fileupload.fail"));
return INPUT;
}
}
}
非常简单,因为我只单纯的用了struts2,没有用spring。所以FileUploadService就硬编码写在里面了。、
图片上传的主要业务类
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import org.csdn.connection.GetConnection;
import org.csdn.vo.Picture;
/**
* @author closewubq
*/
public class FileUploadService {
/**
* 上传图片到数据库
* @param flie
* @return boolean
* 上传是否成功
*/
public boolean fileUpload(File flie) {
FileInputStream in = null;
Connection conn = null;
PreparedStatement ps = null;
try {
in = new FileInputStream(flie);
String sql = "insert into savepicture(picture) value(?)";
conn = GetConnection.getConn();
if (conn == null) {
System.out.println("连接为null");
return false;
}
ps = conn.prepareStatement(sql);
ps.setBinaryStream(1, in, in.available());
if (ps.executeUpdate() > 0) {
GetConnection.close(conn, ps, null);
return true;
} else {
GetConnection.close(conn, ps, null);
return false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
GetConnection.close(conn, ps, null);
return false;
}
}
/**
* 检索所有图片
* @return list
* 返回所有图片记录
*/
public List<Picture> findAll() {
List<Picture> list = new ArrayList<Picture>();
Picture pic = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "select id from savepicture";
conn = GetConnection.getConn();
if (conn == null) {
System.out.println("连接为null");
return null;
}
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
pic = new Picture();
pic.setId(rs.getInt("id"));
list.add(pic);
}
GetConnection.close(conn, ps, rs);
return list;
} catch (Exception e) {
e.printStackTrace();
GetConnection.close(conn, ps, rs);
return null;
}
}
/**
* 根据图片ID获取流对象
* @param id
* @return InputStream
*/
public InputStream getPicById(int id) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
try {
String sql = "select picture from savepicture where id=?";
conn = GetConnection.getConn();
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
if(rs.next()){
is = rs.getBinaryStream("picture");
GetConnection.close(conn, ps, rs);
return is;
}
GetConnection.close(conn, ps, rs);
return null;
} catch (Exception ex) {
ex.printStackTrace();
GetConnection.close(conn, ps, rs);
return null;
}
}
}
简单的写了个jdbc链接的获取类。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 获取数据库链接
* @author closewubq
*/
public class GetConnection {
/**
* 获取数据库连接
* @return Connection
* 返回数据库连接
*/
public static Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost/csdn?user=root&password=";
Connection connection = DriverManager.getConnection(url);
return connection;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 关闭连接释放资源
* @param conn
* @param rs
* @param st
*/
public static void close(Connection conn,PreparedStatement ps,ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(ps!=null)
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
还有保存图片信息的VO
public class Picture {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
输出图片信息的Action
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.csdn.service.FileUploadService;
import com.opensymphony.xwork2.ActionSupport;
/**
* 图片输出
* @author closewubq
*
*/
public class OutPictureAction extends ActionSupport {
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
int id=Integer.parseInt(request.getParameter("id"));
FileUploadService service=new FileUploadService();
InputStream in=service.getPicById(id);
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("image/gif");
int size=in.available();
byte[] image=new byte[size];
in.read(image);
ServletOutputStream out=response.getOutputStream();
out.write(image);
return null;
}
}
over,over好了我们该启动看看效果了: