使用Struts2上傳圖片存取到Mysql中並讀取出來顯示在頁面上
實際上,寫完多文件上傳和下載文章的時候,類似的想法就已經有了,一直沒有實際把它整理好,今天也終於把這方面的一些經驗分享給大家了。
本文涉及到的需求(功能點)大致有:
1. 如何上傳圖片,並把圖片存入資料庫(Mysql)中;
2. 從資料庫中讀取圖片並顯示在頁面中
註:本文使用的是單純的Struts2 + Spring + Hibernate,圖片操作並沒有使用Servlet。
準備工作
本文全部使用Annotation來整合SSH,運用了文件上傳和表單驗證等知識,這些知識都可以在我以前寫的博文中獲取到,包括
1. Struts2下多文件的上傳與下載
http://www.blogjava.net/lishunli/archive/2010/01/07/308614.html
2. 使用Annotation並對DAO層封裝具有分頁功能的S2SH整合實例
http://www.blogjava.net/lishunli/archive/2010/03/10/315055.html
http://www.blogjava.net/lishunli/archive/2010/03/12/315231.html
3. 如何自定義Struts2表單驗證后的錯誤信息顯示格式/樣式
http://www.blogjava.net/lishunli/archive/2010/10/17/335384.html
http://www.blogjava.net/lishunli/archive/2010/01/07/308609.html
如果大家對上面的知識有所欠缺的話和想學習的話,也請大家Google或者看我的blog。謝謝。
開發環境
Struts 2.1.8.1 + Hibernate3 + Spring3+ Mysql5 + Tomcat 7.0.2+ Myeclipse 8.6
流程和主要代碼
創建資料庫
本文會使用User對象(包括username、password、picture等屬性),對應Mysql資料庫的創建腳本如下:
/*
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的類型)
整合SSH
這個步驟請參考使用Annotation並對DAO層封裝具有分頁功能的S2SH整合實例。
主要代碼(知識)
1、 User 類
實際上很簡單,寫出來,主要是讓大家知道這裡面圖片是使用的是什麼類型
@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;
/**
* 省略構造方法和set、get方法
*/
}
2、 AddUserAction類
在add user action,就是真正的把User對象(包括圖像)save到Mysql中。其中這裡使用了Struts2的Annotation,請注意 InterceptorRefs 中 params 的寫法。
關鍵的代碼也就是使用hibernate的createBlob方法來把File類型轉換成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驗證
*/
@Override
public String execute() throws Exception {
if (image != null) {
FileInputStream fin = new FileInputStream(image);// File 轉 InputStream
Blob blob = Hibernate.createBlob(fin);// InputStream 轉 Blob
user.setPicture(blob);
}
userService.save(user);
return SUCCESS;
}
}
3、 addUser.jsp
這個就是一個普通的Input界面,很簡單。想說一下,這裡使用了表單驗證后信息顯示的技術,詳情請見如何自定義Struts2表單驗證后的錯誤信息顯示格式/樣式,也請注意這裡使用了文件上傳控制項,所以要設置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']" /> </font>
<br>
PassWord<s:password name="user.password"></s:password>
<font color="red"> *<s:property value="fieldErrors['user.password']" /> </font>
<br>
Image<s:file name="image"></s:file>
<font color="red"><s:property value="fieldErrors['image']" /> </font>
<br>
<s:submit value="Submit" /><s:reset value="Reset"></s:reset>
</s:form>
4、 GetAllUserAction 類
很簡單,不想貼代碼了,主要是通過Dao查找所有的User,再放到List<User> userList,Struts在調用此Action的使用,通過Iterator List來顯示所有的User。
注意:我這裡僅使用了List,並沒有使用把List放到request中,Struts會通過s:iterator來迭代List,只要我們提供Get List 方法即可。
<s:iterator value="userList" id="user" status="count">
5、 GetImageByIdAction 類
這個類應該是本文的難點和重點,實際上,代碼很簡單的,請大家注意一下幾點
1) 使用Result type「Stream」 :type = "stream" ;
2) Result params 中設置 contentType 和inputName參數,其中
contentType = image/jpeg
inputName = image
inputName 是Action可以通過相關的method獲得InputStream。
注意:下載文件這裡不使用contentType,而是使用contentDisposition參數,詳情請見 Struts2下多文件的上傳與下載
<param name="contentDisposition">attachment;filename="${fileName}"</param>
(Action可以通過Get,Set FileName()來設置和獲得文件名)
實際上這部分的代碼是參考以前某位朋友寫的使用Struts2 生成驗證碼的例子,參考下面的網站
struts2 實現圖片驗證碼
不好意思,現在記不清作者和網站,所以貼上的網址不知道是否是原創或者就是原創,如果有朋友知道,請聯繫我,我會更新鏈接的,謝謝,也很感謝這位朋友的無私奉獻。
@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會調用此方法(也可以使用Method配置其他方法)
* @return
* @throws Exception
*/
public InputStream getImage() throws Exception {
InputStream imageStream = userService.find(id).getPicture().getBinaryStream();
return imageStream;
}
}
6、 allUser.jsp
這個JSP也算知識點比較多,包括一下幾點
1) Action如何取得Image顯示在頁面上
通過調用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 條記錄
(延伸,也可以控制只顯示多少條,給個鏈接,顯示所有的條數)
4) 如果標題長了,省略多餘的字,避免表格撐大
<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">
(單元格固定寬頻,不是隨著內容的變化而變化)
5) 如果沒找到圖片的話,選擇默認圖片顯示
<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.blogjava.net/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>
《解決方案》
程序截圖http://www.blogjava.net/images/blogjava_net/lishunli/Windows-Live-Writer/01c8c1ba8f12_17AD/clip_image001_thumb.pnghttp://www.blogjava.net/images/blogjava_net/lishunli/Windows-Live-Writer/01c8c1ba8f12_17AD/clip_image003_thumb.jpghttp://www.blogjava.net/images/blogjava_net/lishunli/Windows-Live-Writer/01c8c1ba8f12_17AD/clip_image005_thumb.jpg 分享和下載本文全部使用的是Annotation(包括Struts2的所有配置),如果需要使用xml但又覺得轉化成xml配置有困難的話,可以Google,或者聯繫我。謝謝。本篇文章還是可以延伸的,可以做成上傳文件,再判斷文件類型,例如是Image類型的,就顯示出來,如果是Txt等類型,可以提供下載。後續…或者Ending… 源碼在Google Code上https://usc.googlecode.com/svn/ImageUseStruts2AndMysql