使用Struts2上傳圖片存取到Mysql中并讀取出來顯示在頁面上
李順利
Google 標(biāo)簽: 李順利;Struts;圖片;存取;存入;顯示;Mysql;數(shù)據(jù)庫;Blob
索引... 1
關(guān)鍵詞... 1
序... 2
準(zhǔn)備工作... 2
開發(fā)環(huán)境... 3
流程和主要代碼... 3
創(chuàng)建數(shù)據(jù)庫... 3
整合SSH.. 4
主要代碼(知識)... 5
程序截圖... 12
分享和下載... 14
李順利,Struts,圖片,存取,存入,顯示,Mysql,數(shù)據(jù)庫,Blob,
實(shí)際上,寫完多文件上傳和下載文章的時(shí)候,類似的想法就已經(jīng)有了,一直沒有實(shí)際把它整理好,今天也終于把這方面的一些經(jīng)驗(yàn)分享給大家了。
本文涉及到的需求(功能點(diǎn))大致有:
1. 如何上傳圖片,并把圖片存入數(shù)據(jù)庫(Mysql)中;
2. 從數(shù)據(jù)庫中讀取圖片并顯示在頁面中
注:本文使用的是單純的Struts2 + Spring + Hibernate,圖片操作并沒有使用Servlet。
本文全部使用Annotation來整合SSH,運(yùn)用了文件上傳和表單驗(yàn)證等知識,這些知識都可以在我以前寫的博文中獲取到,包括
1. Struts2下多文件的上傳與下載
http://www.tkk7.com/lishunli/archive/2010/01/07/308614.html
2. 使用Annotation并對DAO層封裝具有分頁功能的S2SH整合實(shí)例
http://www.tkk7.com/lishunli/archive/2010/03/10/315055.html
http://www.tkk7.com/lishunli/archive/2010/03/12/315231.html
3. 如何自定義Struts2表單驗(yàn)證后的錯(cuò)誤信息顯示格式/樣式
http://www.tkk7.com/lishunli/archive/2010/10/17/335384.html
http://www.tkk7.com/lishunli/archive/2010/01/07/308609.html
如果大家對上面的知識有所欠缺的話和想學(xué)習(xí)的話,也請大家Google或者看我的blog。謝謝。
Struts 2.1.8.1 + Hibernate3 + Spring3+ Mysql5 + Tomcat 7.0.2+ Myeclipse 8.6
本文會使用User對象(包括username、password、picture等屬性),對應(yīng)Mysql數(shù)據(jù)庫的創(chuàng)建腳本如下:
/*
Source Server : Local
Source Server Version : 50140
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50140
File Encoding : 65001
Date: 2010-11-13 23:23:37
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`picture` longblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8;
|
(請注意pictrue的類型)
這個(gè)步驟請參考使用Annotation并對DAO層封裝具有分頁功能的S2SH整合實(shí)例。
1、 User 類
實(shí)際上很簡單,寫出來,主要是讓大家知道這里面圖片是使用的是什么類型
@Entity
@Table(name = "user", catalog = "test")
public class User implements java.io.Serializable {
private static final long serialVersionUID = 4230186551226007292L;
private Integer id;
private String username;
private String password;
private Blob picture;
/**
* 省略構(gòu)造方法和set、get方法
*/
}
|
2、 AddUserAction類
在add user action,就是真正的把User對象(包括圖像)save到Mysql中。其中這里使用了Struts2的Annotation,請注意 InterceptorRefs 中 params 的寫法。
關(guān)鍵的代碼也就是使用hibernate的createBlob方法來把File類型轉(zhuǎn)換成Blob類型。
Blob blob = Hibernate.createBlob(..)
@Controller
@Scope("prototype")
@Results( { @Result(name = "success", location = "/index.jsp"), @Result(name = "input", location = "addUser.jsp") })
@InterceptorRefs(value = {
@InterceptorRef(value = "fileUpload", params = { "maximumSize", "1048576", "allowedTypes","image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg" }), @InterceptorRef(value = "defaultStack") })
public class AddUserAction extends ActionSupport {
private static final long serialVersionUID = -4829467290275994251L;
private User user;
private File image;
@Resource(name = "org.usc.services.userService")
private IUserService userService;
/**
* 省略 set、get方法和validate驗(yàn)證
*/
@Override
public String execute() throws Exception {
if (image != null) {
FileInputStream fin = new FileInputStream(image);// File 轉(zhuǎn) InputStream
Blob blob = Hibernate.createBlob(fin);// InputStream 轉(zhuǎn) Blob
user.setPicture(blob);
}
userService.save(user);
return SUCCESS;
}
}
|
3、 addUser.jsp
這個(gè)就是一個(gè)普通的Input界面,很簡單。想說一下,這里使用了表單驗(yàn)證后信息顯示的技術(shù),詳情請見如何自定義Struts2表單驗(yàn)證后的錯(cuò)誤信息顯示格式/樣式,也請注意這里使用了文件上傳控件,所以要設(shè)置enctype="multipart/form-data"。
<s:form action="add-user" method="post" theme="simple" enctype="multipart/form-data">
UserName<s:textfield name="user.username"></s:textfield>
<font color="red"> *<s:property value="fieldErrors['user.username'][0]" /> </font>
<br>
PassWord<s:password name="user.password"></s:password>
<font color="red"> *<s:property value="fieldErrors['user.password'][0]" /> </font>
<br>
Image<s:file name="image"></s:file>
<font color="red"><s:property value="fieldErrors['image'][0]" /> </font>
<br>
<s:submit value="Submit" /><s:reset value="Reset"></s:reset>
</s:form>
|
4、 GetAllUserAction 類
很簡單,不想貼代碼了,主要是通過Dao查找所有的User,再放到List<User> userList,Struts在調(diào)用此Action的使用,通過Iterator List來顯示所有的User。
注意:我這里僅使用了List,并沒有使用把List放到request中,Struts會通過s:iterator來迭代List,只要我們提供Get List 方法即可。
<s:iterator value="userList" id="user" status="count">
5、 GetImageByIdAction 類
這個(gè)類應(yīng)該是本文的難點(diǎn)和重點(diǎn),實(shí)際上,代碼很簡單的,請大家注意一下幾點(diǎn)
1) 使用Result type“Stream” :type = "stream" ;
2) Result params 中設(shè)置 contentType 和inputName參數(shù),其中
contentType = image/jpeg
inputName = image
inputName 是Action可以通過相關(guān)的method獲得InputStream。
注意:下載文件這里不使用contentType,而是使用contentDisposition參數(shù),詳情請見 Struts2下多文件的上傳與下載
<param name="contentDisposition">attachment;filename="${fileName}"</param>
(Action可以通過Get,Set FileName()來設(shè)置和獲得文件名)
實(shí)際上這部分的代碼是參考以前某位朋友寫的使用Struts2 生成驗(yàn)證碼的例子,參考下面的網(wǎng)站
struts2 實(shí)現(xiàn)圖片驗(yàn)證碼
不好意思,現(xiàn)在記不清作者和網(wǎng)站,所以貼上的網(wǎng)址不知道是否是原創(chuàng)或者就是原創(chuàng),如果有朋友知道,請聯(lián)系我,我會更新鏈接的,謝謝,也很感謝這位朋友的無私奉獻(xiàn)。
@Controller
@Scope("prototype")
@Results( { @Result(type = "stream", params = { "contentType", "image/jpeg", "inputName", "image" }) })
public class GetImageByIdAction extends ActionSupport {
private static final long serialVersionUID = 207987943720580274L;
private Integer id;
@Resource(name = "org.usc.services.userService")
private IUserService userService;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setUserService(IUserService userService) {
this.userService = userService;
}
/**
* 注意這里的方法名,和上面配置params中inputName是一致的,Struts會調(diào)用此方法(也可以使用Method配置其他方法)
* @return
* @throws Exception
*/
public InputStream getImage() throws Exception {
InputStream imageStream = userService.find(id).getPicture().getBinaryStream();
return imageStream;
}
}
|
6、 allUser.jsp
這個(gè)JSP也算知識點(diǎn)比較多,包括一下幾點(diǎn)
1) Action如何取得Image顯示在頁面上
通過調(diào)用get-image-by-id.action來獲取圖片
2) list如何Iterator
<s:iterator value="userList" id="user" status="count">
// 注意value
3) Table可以限制每行顯示多少條記錄
<s:if test="#count.index % 6 == 0">
<tr>
</s:if>
<s:if test="(#count.index + 1) % 6 == 0">
</tr>
</s:if>
// 每行顯示6 條記錄
(延伸,也可以控制只顯示多少條,給個(gè)鏈接,顯示所有的條數(shù))
4) 如果標(biāo)題長了,省略多余的字,避免表格撐大
<td width="800" height="120" style="width: 200px; word-break: break-all" align="center">
<div style="width: 200x; height: 20px; border: 1px; overflow: hidden; text-overflow: ellipsis">
(單元格固定寬帶,不是隨著內(nèi)容的變化而變化)
5) 如果沒找到圖片的話,選擇默認(rèn)圖片顯示
<img … onerror="javascript:this.src='images/default.png'" />
<s:form action="get-all-user" method="post" theme="simple">
<s:if test="userList.size">
<table width="75%" align="center">
<s:iterator value="userList" id="user" status="count">
<s:if test="#count.index % 6 == 0">
<tr>
</s:if>
<td width="800" height="120" style="width: 200px; word-break: break-all" align="center">
<a href="http://www.tkk7.com/lishunli/" target="_blank">
<img src="<%=basePath + "get-image-by-id.action?id="%><s:property value="#user.id"/>" width="100" height="100" alt="照片"
title="<s:property value="#user.username" />" onerror="javascript:this.src='images/default.png'" />
</a>
<div style="width: 200x; height: 20px; border: 1px; overflow: hidden; text-overflow: ellipsis">
<s:property value="#user.username" />
</div>
</td>
<s:if test="(#count.index + 1) % 6 == 0">
</tr>
</s:if>
</s:iterator>
</table>
</s:if>
</s:form>
|



本文全部使用的是Annotation(包括Struts2的所有配置),如果需要使用xml但又覺得轉(zhuǎn)化成xml配置有困難的話,可以Google,或者聯(lián)系我。謝謝。
本篇文章還是可以延伸的,可以做成上傳文件,再判斷文件類型,例如是Image類型的,就顯示出來,如果是Txt等類型,可以提供下載。后續(xù)…或者Ending…
源碼在Google Code上
https://usc.googlecode.com/svn/ImageUseStruts2AndMysql
源碼和相關(guān)參考提供下載
Via http://pan.baidu.com/s/1ntulO4D
(源碼和所需Jar)
文 件 名:ImageUseStruts2AndMysql.zip
其中 ImageUseStruts2AndMysql.zip 有下面的文件

如果有什么建議或意見可以通過微博 http://weibo.com/lishunli(左上側(cè)直接加關(guān)注) 或 QQ:506817493 或 Email:leeshunli@qq.com 或 MSN:lishunli@live.com(QQ白天經(jīng)常不在線,建議微博或者M(jìn)SN 交流,謝謝),大家一起交流學(xué)習(xí)。
這篇博文是基于(Struts2下多文件的上傳與下載)以前寫的,如果有什么不明白的地方,也可以前往看看,謝謝。
最后弱弱地說一下,如果可以的話,轉(zhuǎn)載請?zhí)峁┰璘RL,謝謝。
順利寫于2010年11月14日
博客中的一些下載已經(jīng)放到了百度云了,請根據(jù)需要下載。【點(diǎn)我去百度云下載】
最后弱弱地說一下,如果可以的話,轉(zhuǎn)載請?zhí)峁┏鎏?
),謝謝。
posted on 2010-11-14 01:43
李順利 閱讀(13303)
評論(16) 編輯 收藏