EXTJS配合Struts2的图片上传(可预览)

3. import javax.servlet.http.HttpServletRequest;
4. import javax.servlet.http.HttpServletResponse;
5.
6. import org.apache.struts2.interceptor.ServletRequestAware;
7. import org.apache.struts2.interceptor.ServletResponseAware;
8.
9. import cn.com.ajaxbear.vo.Account;
10.
11. import com.opensymphony.xwork2.ActionSupport;
12.
13. public class BaseAction extends ActionSupport implements ServletRequestAware,
14. ServletResponseAware {
15. private static final long serialVersionUID = -1513311332990213727L;
16.
17. protected HttpServletResponse response;
18.
19. protected HttpServletRequest request;
20.
21. public void setServletRequest(HttpServletRequest request) {
22. this.request = request;
23. }
24.
25. public void setServletResponse(HttpServletResponse response) {
26. this.response = response;
27. }
28.
29. protected Account getUser(HttpServletRequest request){
30. return (Account)request.getSession().getAttribute("user");
31. }
32.
33. protected void setUser(HttpServletRequest request, Account account){
34. request.getSession().setAttribute("user", account);
35. }
36.
37. protected void destroyUser(HttpServletRequest request){
38. request.getSession().removeAttribute("user");
39. }
40.
41. }

package cn.com.ajaxbear.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import cn.com.ajaxbear.vo.Account;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private static final long serialVersionUID = -1513311332990213727L;

protected HttpServletResponse response;

protected HttpServletRequest request;

public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

public void setServletResponse(HttpServletResponse response) {
this.response = response;
}

protected Account getUser(HttpServletRequest request){
return (Account)request.getSession().getAttribute("user");
}

protected void setUser(HttpServletRequest request, Account account){
request.getSession().setAttribute("user", account);
}

protected void destroyUser(HttpServletRequest request){
request.getSession().removeAttribute("user");
}

}


然后我们新建一个Action,名字为UploadAction:
Java 代码

1. package cn.com.ajaxbear.action;
2.
3. import java.io.File;
4. import java.io.FileInputStream;
5. import java.io.FileOutputStream;
6. import java.util.UUID;
7.
8. import org.apache.struts2.ServletActionContext;
9.
10. import cn.com.ajaxbear.util.XResponse;
11.
12. public class UploadAction extends BaseAction {
13.
14. private File upload;
15. private String uploadContentType;
16. public File getUpload() {
17. return upload;
18. }
19.
20. public void setUpload(File upload) {
21. this.upload = upload;
22. }
23.
24. public String getUploadContentType() {
25. return uploadContentType;
26. }
27.
28. public void setUploadContentType(String uploadContentType) {
29. this.uploadContentType = uploadContentType;
30. }
31.
32. public String getUploadFileName() {
33. return uploadFileName;
34. }
35.
36. public void setUploadFileName(String uploadFileName) {
37. this.uploadFileName = uploadFileName;
38. }
39.
40. // 上传文件的文件名
41. private String uploadFileName;
42.
43. private String getFileExp(String name){
44. int pos = name.lastIndexOf(".");
45.
46. return name.substring(pos);
47. }
48.
49. @Override
50. public String execute() throws Exception {
51. //首先判断用户是否曾经上传过,如果上传过,则删掉原来的文件(这里我没考虑其他情况,考虑周全还要写一些代码)
52. String oldImageName = request.getParameter("oldImageName");
53. //如果存在则删除
54. if (!"noImage".equalsIgnoreCase(oldImageName)) {
55. File oldFile = new File(ServletActionContext
56. .getServletContext().getRealPath("/")
57. + "UploadImages" + File.separator+oldImageName);
58. oldFile.delete();
59. }
60. System.out.println(oldImageName);
61. //为用户新上传的图片新取一个名字
62. String newName = UUID.randomUUID().toString();
63. //获取用户上传的图片格式
64. String exp = getFileExp(uploadFileName);
65. //将文件写入文件夹
66. FileOutputStream fos = new FileOutputStream(ServletActionContext
67. .getServletContext().getRealPath("/")
68. + "UploadImages" + File.separator + newName+exp);
69. FileInputStream fis = new FileInputStream(upload);
70. byte[] buffer = new byte[10240];
71. int len = 0;
72. int total = fis.available();
73. System.out.println("文件大小为:"+total);
74. while ((len = fis.read(buffer)) > 0) {
75. fos.write(buffer, 0, len);
76. fos.flush();
77. }
78. fis.close();
79. fos.close();
80. //返回图片名称(路径我是在前台写死了的),注意返回的contentType不能是text/json;
81. XResponse.sendMSG(response, "{success : true,msg:'"+newName+exp+"'}","text/html; charset=utf-8");
82. return NONE;
83. }
84. }

package cn.com.ajaxbear.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;

import cn.com.ajaxbear.util.XResponse;

public class UploadAction extends BaseAction {

private File upload;
private String uploadContentType;
public File getUpload() {
return upload;
}

public void setUpload(File upload) {
this.upload = upload;
}

public String getUploadContentType() {
return uploadContentType;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public String getUploadFileName() {
return uploadFileName;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

// 上传文件的文件名
private String uploadFileName;

private String getFileExp(String name){
int pos = name.lastIndexOf(".");

return name.substring(pos);
}

@Override
public String execute() throws Exception {
//首先判断用户是否曾经上传过,如果上传过,则删掉原来的文件(这里我没考虑其他情况,考虑周全还要写一些代码)
String oldImageName = request.getParameter("oldImageName");
//如果存在则删除
if (!"noImage".equalsIgnoreCase(oldImageName)) {
File oldFile = new File(ServletActionContext
.getServletContext().getRealPath("/")
+ "UploadImages" + File.separator+oldImageName);
oldFile.delete();
}
System.out.println(oldImageName);
//为用户新上传的图片新取一个名字
String newName = UUID.randomUUID().toString();
//获取用户上传的图片格式
String exp = getFileExp(uploadFileName);
//将文件写入文件夹
FileOutputStream fos = new FileOutputStream(ServletActionContext
.getServletContext().getRealPath("/")
+ "UploadImages" + File.separator + newName+exp);
FileInputStream fis = new FileInputStream(upload);
byte[] buffer = new byte[10240];
int len = 0;
int total = fis.available();
System.out.println("文件大小为:"+total);
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
fos.flush();
}
fis.close();
fos.close();
//返回图片名称(路径我是在前台写死了的),注意返回的contentType不能是text/json;
XResponse.sendMSG(response, "{success : true,msg:'"+newName+exp+"'}","text/html; charset=utf-8");
return NONE;
}
}


XResponse的代码:
Java 代码

1. package cn.com.ajaxbear.util;
2.
3. import java.io.IOException;
4.
5. import javax.servlet.http.HttpServletResponse;
6.
7. import org.apache.commons.logging.Log;
8. import org.apache.commons.logging.LogFactory;
9.
10. public class XResponse {
11. public XResponse() {
12. }
13.
14. protected static final Log log = LogFactory.getLog(XResponse.class);
15.
16. public static void sendMSG(HttpServletResponse response, Object jsonData,
17. String... strings) {
18. if (strings.length != 0) {
19. response.setContentType(strings[0]);
20. }else{
21. response.setContentType("text/json; charset=utf-8");
22. }
23. try {
24. log.debug("<-----JSON:" + jsonData.toString());
25. response.getWriter().write(jsonData.toString());
26. response.getWriter().flush();
27. } catch (IOException e) {
28. log.error(e.getMessage());
29. // e.printStackTrace();
30. }
31. };
32. }

package cn.com.ajaxbear.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class XResponse {
public XResponse() {
}

protected static final Log log = LogFactory.getLog(XResponse.class);

public static void sendMSG(HttpServletResponse response, Object jsonData,
String... strings) {
if (strings.length != 0) {
response.setContentType(strings[0]);
}else{
response.setContentType("text/json; charset=utf-8");
}
try {
log.debug("<-----JSON:" + jsonData.toString());
response.getWriter().write(jsonData.toString());
response.getWriter().flush();
} catch (IOException e) {
log.error(e.getMessage());
// e.printStackTrace();
}
};
}


编写Struts2的配置文件:
Xml代码

1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
3. <struts>
4. <package name="cn.com.ajaxbear.action" extends="struts-default"
5. namespace="/">
6. <action name="uploadAction" class="UploadAction">
7. <interceptor-ref name="fileUpload">
8. <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
9. <param name="maximumSize">20000000000</param>
10. </interceptor-ref>
11. <interceptor-ref name="defaultStack"/>
12. </action>
13. </package>
14. </struts>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="cn.com.ajaxbear.action" extends="struts-default"
namespace="/">
<action name="uploadAction" class="UploadAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
<param name="maximumSize">20000000000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
</action>
</package>
</struts>


开始编写界面:
首先写一个图片组件,用于显示图片:
Js代码

1. Ext.namespace("HRM.External.Image");
2. /**
3. * @author <a href="mailto:andy_ghg@163.com"& gt;葛昊</a></br>
4. * @version 1.0
5. * @description 图片组件
6. * @class HRM.External.Image
7. * @extends Ext.BoxComponent
8. */
9. HRM.External.Image = Ext.extend(Ext.BoxComponent, {
10. imageSrc : "",
11. initComponent : function() {
12. HRM.External.Image.superclass.initComponent.call(this, arguments);
13. this.on("render",function(){
14. this.setImage(this.imageSrc);
15. },this);
16. },
17. /**
18. * 获取XTemplate对象
19. * @return {@link Ext.XTemplate}
20. */
21. getXTemplate : function() {
22. return this.xtpl || (function() {
23. this.xtpl = new Ext.XTemplate("<div><img id='{id}' src='{imgSrc}' height='{height}' width='{width}' border='{border}' /></div>");
24. return this.xtpl;
25. }.createDelegate(this))();
26. },
27. /**
28. * 获取图片属性对象
29. * @return {Object}
30. */
31. getImage : function() {
32. return this.imageData || (function() {
33. this.imageData = {
34. id : this.getId()+"_img",
35. imgSrc : "",
36. height : this.height,
37. width : this.width,
38. border : 0
39. }
40. return this.imageData;
41. }.createDelegate(this))();
42. },
43. /**
44. * 设置图片路径
45. * @param {String} src 图片路径
46. */
47. setImage : function(src) {
48. this.getImage().imgSrc = src;
49. console.log(this.getImage());
50. this.getXTemplate().overwrite(this.getEl(),this.getImage());
51. }
52. });
53.
54. Ext.reg("ximage",HRM.External.Image);

Ext.namespace("HRM.External.Image");
/**
* @author <a href="mailto:andy_ghg@163.com">葛昊</a></br>
* @version 1.0
* @description 图片组件
* @class HRM.External.Image
* @extends Ext.BoxComponent
*/
HRM.External.Image = Ext.extend(Ext.BoxComponent, {
imageSrc : "",
initComponent : function() {
HRM.External.Image.superclass.initComponent.call(this, arguments);
this.on("render",function(){
this.setImage(this.imageSrc);
},this);
},
/**
* 获取XTemplate对象
* @return {@link Ext.XTemplate}
*/
getXTemplate : function() {
return this.xtpl || (function() {
this.xtpl = new Ext.XTemplate("<div><img id='{id}' src='{imgSrc}' height='{height}' width='{width}' border='{border}' /></div>");
return this.xtpl;
}.createDelegate(this))();
},
/**
* 获取图片属性对象
* @return {Object}
*/
getImage : function() {
return this.imageData || (function() {
this.imageData = {
id : this.getId()+"_img",
imgSrc : "",
height : this.height,
width : this.width,
border : 0
}
return this.imageData;
}.createDelegate(this))();
},
/**
* 设置图片路径
* @param {String} src 图片路径
*/
setImage : function(src) {
this.getImage().imgSrc = src;
console.log(this.getImage());
this.getXTemplate().overwrite(this.getEl(),this.getImage());
}
});

Ext.reg("ximage",HRM.External.Image);


再写一个上传组件(使用官方插件Ext.ux.form.FileUploadField):
Js代码

1. HRM.External.ImageUpload = Ext.extend(Ext.Container, {
2. url : "",
3. style : "padding : 5px",
4. initComponent : function() {
5. HRM.External.ImageUpload.superclass.initComponent.call(this, arguments);
6. this.addEvents("selected");
7. this.add(this.getImage(true), this.getUploadField(true));
8. },
9. getImage : function(autoCreate) {
10. if (autoCreate) {
11. return this.image || (function() {
12. this.image = new HRM.External.Image({
13. height : this.height - 35,
14. width : this.width - 10,
15. imageSrc : "src/Resources/images/default.gif"
16. });
17. return this.image;
18. }.createDelegate(this))();
19. } else {
20. return this.image || {};
21. }
22. },
23. getUploadField : function(autoCreate) {
24. if (autoCreate) {
25. return this.uploadField || (function() {
26. //Ext.ux.Form.FileUploadField是官方的插件,可以再例子里看到它
27. this.uploadField = new Ext.ux.form.FileUploadField({
28. width : this.width,
29. name : "upload",
30. buttonText : "选择照片.."
31. });
32. this.uploadField.on("fileselected", function(obj, value) {
33. this.fireEvent("selected");
34. }, this);
35. return this.uploadField;
36. }.createDelegate(this))();
37. } else {
38. return this.uploadField || {};
39. }
40. }
41. });

HRM.External.ImageUpload = Ext.extend(Ext.Container, {
url : "",
style : "padding : 5px",
initComponent : function() {
HRM.External.ImageUpload.superclass.initComponent.call(this, arguments);
this.addEvents("selected");
this.add(this.getImage(true), this.getUploadField(true));
},
getImage : function(autoCreate) {
if (autoCreate) {
return this.image || (function() {
this.image = new HRM.External.Image({
height : this.height - 35,
width : this.width - 10,
imageSrc : "src/Resources/images/default.gif"
});
return this.image;
}.createDelegate(this))();
} else {
return this.image || {};
}
},
getUploadField : function(autoCreate) {
if (autoCreate) {
return this.uploadField || (function() {
//Ext.ux.Form.FileUploadField是官方的插件,可以再例子里看到它
this.uploadField = new Ext.ux.form.FileUploadField({
width : this.width,
name : "upload",
buttonText : "选择照片.."
});
this.uploadField.on("fileselected", function(obj, value) {
this.fireEvent("selected");
}, this);
return this.uploadField;
}.createDelegate(this))();
} else {
return this.uploadField || {};
}
}
});


两个组件写好之后,开始编写应用界面:
Java 代码

1. Ext.namespace("HRM.Employee.EmployeeInfo");
2.
3. HRM.Employee.EmployeeInfo = Ext.extend(Ext.Container, {
4. layout : "fit",
5. resizable : false,
6. autoHeight : true,
7. PROJECT_NAME : "/HRM/",
8. style : "padding : 5px",
9. initComponent : function() {
10. HRM.Employee.EmployeeInfo.superclass.initComponent.call(this, arguments);
11. this.add(this.getFormPanel(true));
12. },
13. getFormPanel : function(autoCreate) {
14. if (autoCreate) {
15. return this.formPanel || (function() {
16. var comp = new Ext.Container({
17. layout : "column",
18. defaults : {
19. columnWidth : .5,
20. border : false
21. },
22. autoHeight : true,
23. items : [this.getUploadForm(), this.getEmployeeBaseForm()]
24. });
25. this.formPanel = new Ext.Container({
26. autoHeight : true,
27. baseCls : "x-plain",
28. border : false,
29. defaults : {border : false},
30. items : [comp, this.getBotForm()]
31. });
32. return this.formPanel;
33. }.createDelegate(this))();
34. } else {
35. return this.formPanel || {};
36. }
37. },
38. // private
39. getEmployeeBaseForm : function() {
40. return this.empBaseForm || (function() {
41. this.empBaseForm = new Ext.FormPanel({
42. defaultType : "textfield",
43. defaults : {
44. anchor : "100%"
45. },
46. labelWidth : 55,
47. items : [{
48. fieldLabel : "姓名",
49. allowBlank : false,
50. name : "name"
51. }, {
52. xtype : 'radiogroup',
53. fieldLabel : '性别',
54. items : [{
55. boxLabel : '男',
56. name : 'sex',
57. inputValue : "男",
58. checked : true
59. }, {
60. boxLabel : '女',
61. name : 'sex',
62. inputValue : "女"
63. }]
64. }, {
65. xtype : "datefield",
66. minValue : "1949-12-23",
67. maxValue : new Date().format("Y-m-d"),
68. fieldLabel : "生日",
69. name : "birthday"
70. }, {
71. fieldLabel : "固话号码",
72. name : "tel"
73. }, {
74. fieldLabel : "手机号码",
75. name : "mobil"
76. }, {
77. fieldLabel : "电子邮箱",
78. name : "email",
79. emptyText : "例如andy_ghg@163.com",
80. vtype : "email"
81. }, {
82. xtype : 'radiogroup',
83. fieldLabel : '婚姻状况',
84. items : [{
85. boxLabel : '已婚',
86. name : 'marriage',
87. inputValue : 1
88. }, {
89. boxLabel : "未婚",
90. name : 'marriage',
91. checked : true,
92. inputValue : 0
93. }]
94. }, {
95. xtype : "combo",
96. fieldLabel : "政治面貌",
97. triggerAction : "all",
98. mode : "local",
99. displayField : "value",
100. valueField : "value",
101. store : new Ext.data.SimpleStore({
102. fields : ["i", "value"],
103. data : [["共青团员", "共青团员"], ["中共党员", "中共党员"], ["无党派人士", "无党派人士"]]
104. })
105. }]
106. })
107. return this.empBaseForm;
108. }.createDelegate(this))();
109. },
110. getBotForm : function() {
111. return this.botForm || (function() {
112. this.botForm = new Ext.FormPanel({
113. defaultType : "textfield",
114. defaults : {
115. anchor : "100%"
116. },
117. labelWidth : 55,
118. items : [{
119. fieldLabel : "住址"
120. }, {
121. fieldLabel : "籍贯"
122. }]
123. })
124. return this.botForm;
125. }.createDelegate(this))();
126. },
127. //主要看这里,以及这里面的selected事件的监听
128. getUploadForm : function() {
129. return this.uploadForm || (function() {
130. this.uploadField = new HRM.External.ImageUpload({
131. height : 225
132. });
133. this.uploadForm = new Ext.FormPanel({
134. fileUpload : true,
135. items : this.uploadField
136. });
137. var oldImageName = "noImage";
138. this.uploadField.on("selected", function() {
139. console.log("进来了");
140. this.uploadForm.getForm().submit({
141. method : "POST",
142. scope : this,
143. params : {
144. oldImageName : oldImageName
145. },
146. url : "/HRM/uploadAction.do",
147. success : function(form,action){
148. console.log(action.result.msg);
149. this.uploadField.getImage().setImage("UploadImages/"+action.result.msg);
150. oldImageName = action.result.msg;
151. },
152. failure : function(form, action) {
153. console.log(action.result.data);
154. }
155. })
156. },this);
157. return this.uploadForm;
158. }.createDelegate(this))();
159. },
160. getForm : function() {
161. return this.getFormPanel().getForm();
162. }
163. })
164.
165. Ext.onReady(function() {
166. var c = new HRM.Employee.EmployeeInfo({
167. width : 500,
168. autoHeight : true,
169. renderTo : Ext.getBody()
170. });
171. })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值