- 浏览: 70674 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
wukele:
呵呵,整理附件下载该多好。
Java实时获取oracle变更 -
zz_1999:
lz,你piggyback方式试过没,我试了客户端没反映。
dwr reverse ajax -
jroad:
还有这个DefaultScriptSession 和scrip ...
DWR3-ReverseAjax-半推实现 -
jroad:
有点不明白,朋友的sessionmap从那时来的,请教下.
...
DWR3-ReverseAjax-半推实现
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. })
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. })
相关推荐
标签"Java extjs struts2"进一步确认了这个项目是用Java后端配合ExtJs前端实现的。在Struts2中,文件上传通常会涉及Action类,该类接收文件参数,然后调用Service层进行业务处理。同时,ExtJs的Ajax请求需要与Struts...
网上有些这样的例子,但是下了几个都没有跑起来,哎,希望那些发文章的人要发就发全的,别发个半生不熟的。... 现在自己整理了一个Struts2+ExtJS2实现文异步文件上传,没法上传图片无法看到效果,直接上源码吧。
在本文中,我们将深入探讨如何使用ExtJS 4与Struts2框架实现文件上传功能。ExtJS是一个强大的JavaScript库,提供了丰富的用户界面组件,而Struts2是Java Web开发中的一个MVC框架,用于处理后端业务逻辑。下面,我们...
在"ExtJS+Struts2"的组合中,前端使用ExtJS进行界面设计和用户交互处理。例如,"简单增删改"功能通常会涉及到ExtJS的Grid Panel组件,它能展示数据表格,支持行操作,如添加新记录、删除现有记录以及编辑单元格内容...
在本场景中,"extjs struts2 多图片批量上传控件"是一个集成解决方案,允许用户通过ExtJS前端框架批量上传多张图片,并通过Struts2后端框架进行处理。 **ExtJS** 是一个基于JavaScript的UI库,它提供了丰富的组件和...
EXTJS4、STRUTS2和JAVA是Web开发中常用的三大技术框架,它们结合使用可以构建功能丰富的交互式用户界面和高效的企业级应用。在这个"EXTJS4+STRUTS2+JAVA增删改查"的例子中,我们将深入探讨这三个技术如何协同工作,...
标题 "extjs 跟 struts+json" 暗示了本文将探讨如何使用ExtJS框架与Struts框架结合,通过JSON数据格式进行交互。ExtJS是一个强大的JavaScript库,用于构建富客户端Web应用程序,而Struts是Java Web开发中的一个MVC...
一个运用Extjs,Struts2, json,iterator技术构建的iterator_jsonDemo2。iterator_jsonDemo1的链接:http://download.csdn.net/detail/cafebar123/8816409 运用了Extjs,Struts2, json,iterator技术, 将数据从...
ExtJs + Struts2 + JSON 是一种常见的前端与后端数据交互的技术组合,常用于构建富客户端应用。这里我们详细探讨一下这三个技术组件以及它们如何协同工作。 首先,ExtJs 是一个JavaScript库,用于创建复杂的、用户...
ExtJS与Struts2是两种在Web开发中广泛使用的开源技术。ExtJS是一个JavaScript库,提供了丰富的用户界面组件和强大的数据处理能力,而Struts2则是一个基于MVC设计模式的Java Web框架,用于简化应用的开发流程。将这...
EXTJS提供了丰富的UI组件和优秀的用户体验,STRUTS2则负责处理后端逻辑,两者相结合,可以构建出高效、可维护的现代Web应用程序。通过不断学习和实践,开发者可以更好地掌握这两个框架的集成技巧,提高开发效率。
本文将深入探讨如何使用Struts2和ExtJS3实现单文件和多文件的上传功能。 首先,我们要理解文件上传的基本流程。在Web应用中,用户通过浏览器选择本地文件,然后这些文件的数据被封装到HTTP请求中发送到服务器。...
在批量图片预览上传场景中,EXTJS可以用于构建前端交互界面,处理用户的选择和上传逻辑。 1. **EXTJS组件使用**:EXTJS 提供了FileField组件,可以用来接收用户选择的文件。配合UploadButton或FormPanel,可以方便...
7. **页面布局**:ExtJS提供了丰富的布局管理器,可以配合Struts2的视图层,实现动态、响应式的页面布局。 总的来说,ExtJS与Struts2的结合,既利用了ExtJS的强大前端展示能力,又发挥了Struts2在后端的业务处理...
在本文中,我们将深入探讨如何使用ExtJS 4和Struts2框架实现省市区三级联动的完整示例。这个示例适用于需要在Web应用程序中实现地理区域选择功能的情况,例如用户地址输入。以下是对该技术栈及其实现方法的详细说明...
ExtJS和Struts2是两种在Web开发中广泛使用的开源技术。ExtJS是一个JavaScript库,提供了丰富的用户界面组件,如数据网格、图表、表单等,用于构建富客户端应用程序。Struts2则是一个基于MVC设计模式的Java Web框架,...
### 搭建EXTJS和STRUTS2框架(ext和struts2简单实例) #### 一、概述 本文档将详细介绍如何在Java Web项目中搭建EXTJS和STRUTS2框架,并通过一个简单的实例来展示如何使这两个技术协同工作。EXTJS是一个用于构建交互...
【图书管理系统源码(ExtJs+struts2+hibernate+spring)】是一个基于Web的软件项目,它展示了如何整合多种技术来构建一个实际的应用系统。这个管理系统使用了前端框架ExtJs,后端MVC框架Struts2,持久层框架...
ExtJS、Struts2和JDBC是Web开发中常见的技术栈,它们的结合可以构建功能丰富的交互式Web应用。这个小例子提供了一个基于这些技术的简单增删改查(CRUD)操作的实现,对于初学者来说是一个很好的学习资源。 ExtJS是...
本示例中,EXTJS、Struts2和JSON共同用于制作一个登录窗口。 首先,我们需要在项目中引入必要的库文件,如描述中所示,包括Struts2的核心库和其他依赖库,例如Commons-logging、Freemarker、Ognl等。这些库文件是...