- 浏览: 290600 次
- 性别:
- 来自: 扬州
文章分类
最新评论
-
wanglujiede:
幸亏看了这里,关于store的proxy的params问题顶一 ...
ExtJS 4.0 的改变(仅发表我发现的) -
freddie:
现在都extjs5了,感觉extjs3-extjs4变化挺大的 ...
ExtJS 4.0 的改变--较为完整的介绍。 -
jiangzi100:
写的真的很好,输入EXT这个工具很烂
EXTJS组件化(一)----建立你的思想 -
我飞我是飞飞:
StringHttpMessageConverter,我是3. ...
StringHttpMessageConverter乱码问题的解决(Spring 3.2) -
restmad:
999
EXTJS组件化(一)----建立你的思想
最近一直在用Struts2,忽然心血来潮想做个图片上传并预览的功能,这个功能我其实在Struts1里早就玩过了的,本来以为Struts2无非也就那么一回事,但是测试成功之后发现,过程还是颇具周折的.....
我是直接拷贝的工程里的代码,所以可能有一部分无关的代码,懒得去弄了
废话不多说,上例子代码:
首先,我们新建一个BaseAction,这个Action主要就是为了实现那两个接口,我就直接把我工程里的Copy过来:
然后我们新建一个Action,名字为UploadAction:
XResponse的代码:
编写Struts2的配置文件:
开始编写界面:
首先写一个图片组件,用于显示图片:
再写一个上传组件(使用官方插件Ext.ux.form.FileUploadField):
两个组件写好之后,开始编写应用界面:
我是直接拷贝的工程里的代码,所以可能有一部分无关的代码,懒得去弄了
废话不多说,上例子代码:
首先,我们新建一个BaseAction,这个Action主要就是为了实现那两个接口,我就直接把我工程里的Copy过来:
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:
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的代码:
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 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>
开始编写界面:
首先写一个图片组件,用于显示图片:
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):
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 || {}; } } });
两个组件写好之后,开始编写应用界面:
Ext.namespace("HRM.Employee.EmployeeInfo"); HRM.Employee.EmployeeInfo = Ext.extend(Ext.Container, { layout : "fit", resizable : false, autoHeight : true, PROJECT_NAME : "/HRM/", style : "padding : 5px", initComponent : function() { HRM.Employee.EmployeeInfo.superclass.initComponent.call(this, arguments); this.add(this.getFormPanel(true)); }, getFormPanel : function(autoCreate) { if (autoCreate) { return this.formPanel || (function() { var comp = new Ext.Container({ layout : "column", defaults : { columnWidth : .5, border : false }, autoHeight : true, items : [this.getUploadForm(), this.getEmployeeBaseForm()] }); this.formPanel = new Ext.Container({ autoHeight : true, baseCls : "x-plain", border : false, defaults : {border : false}, items : [comp, this.getBotForm()] }); return this.formPanel; }.createDelegate(this))(); } else { return this.formPanel || {}; } }, // private getEmployeeBaseForm : function() { return this.empBaseForm || (function() { this.empBaseForm = new Ext.FormPanel({ defaultType : "textfield", defaults : { anchor : "100%" }, labelWidth : 55, items : [{ fieldLabel : "姓名", allowBlank : false, name : "name" }, { xtype : 'radiogroup', fieldLabel : '性别', items : [{ boxLabel : '男', name : 'sex', inputValue : "男", checked : true }, { boxLabel : '女', name : 'sex', inputValue : "女" }] }, { xtype : "datefield", minValue : "1949-12-23", maxValue : new Date().format("Y-m-d"), fieldLabel : "生日", name : "birthday" }, { fieldLabel : "固话号码", name : "tel" }, { fieldLabel : "手机号码", name : "mobil" }, { fieldLabel : "电子邮箱", name : "email", emptyText : "例如andy_ghg@163.com", vtype : "email" }, { xtype : 'radiogroup', fieldLabel : '婚姻状况', items : [{ boxLabel : '已婚', name : 'marriage', inputValue : 1 }, { boxLabel : "未婚", name : 'marriage', checked : true, inputValue : 0 }] }, { xtype : "combo", fieldLabel : "政治面貌", triggerAction : "all", mode : "local", displayField : "value", valueField : "value", store : new Ext.data.SimpleStore({ fields : ["i", "value"], data : [["共青团员", "共青团员"], ["中共党员", "中共党员"], ["无党派人士", "无党派人士"]] }) }] }) return this.empBaseForm; }.createDelegate(this))(); }, getBotForm : function() { return this.botForm || (function() { this.botForm = new Ext.FormPanel({ defaultType : "textfield", defaults : { anchor : "100%" }, labelWidth : 55, items : [{ fieldLabel : "住址" }, { fieldLabel : "籍贯" }] }) return this.botForm; }.createDelegate(this))(); }, //主要看这里,以及这里面的selected事件的监听 getUploadForm : function() { return this.uploadForm || (function() { this.uploadField = new HRM.External.ImageUpload({ height : 225 }); this.uploadForm = new Ext.FormPanel({ fileUpload : true, items : this.uploadField }); var oldImageName = "noImage"; this.uploadField.on("selected", function() { console.log("进来了"); this.uploadForm.getForm().submit({ method : "POST", scope : this, params : { oldImageName : oldImageName }, url : "/HRM/uploadAction.do", success : function(form,action){ console.log(action.result.msg); this.uploadField.getImage().setImage("UploadImages/"+action.result.msg); oldImageName = action.result.msg; }, failure : function(form, action) { console.log(action.result.data); } }) },this); return this.uploadForm; }.createDelegate(this))(); }, getForm : function() { return this.getFormPanel().getForm(); } }) Ext.onReady(function() { var c = new HRM.Employee.EmployeeInfo({ width : 500, autoHeight : true, renderTo : Ext.getBody() }); })
评论
2 楼
zuyali
2012-02-08
你好,请教个问题,图片是被存到服务器下的目录,在this.uploadField.getImage().setImage("UploadImages/"+action.result.msg); 显示图片的时候显示不出来
1 楼
yangguo
2011-08-05
不错
发表评论
-
StringHttpMessageConverter乱码问题的解决(Spring 3.2)
2013-02-03 23:05 18807特别标注了是Spring 3.2,在网上搜了半天,很多配置应该 ... -
Ext JS 4.x任意组件放入ComboBox的下拉框。例如tree、grid等。
2012-12-29 21:10 2213移步到http://www.uniorder.com/2013 ... -
Ext JS 4.1.1整合Kindeditor
2012-11-29 20:11 5292整合Kindeditor比CKEditor要简单许多许多(CK ... -
Ext JS 4.1.1整合CKEditor。
2012-11-28 23:44 2677Ext.define('GB.view.CKeditor' ... -
用Java反射写的生成ExtJS MVC model文件的类。
2012-10-24 22:11 3133如果你也在写Ext JS的MVC,恰好又遇到了类似下面的这个类 ... -
Error setting expression 'ext-gen1500' with value
2011-08-09 18:34 3609首先查看devMode是否设置为false,否则查看你提交的表 ... -
ExtJS 4.0 的改变--较为完整的介绍。
2011-07-26 22:14 37831惯例,看之前先看看我的很久很久以前的学习笔记(就是那个Word ... -
ExtJS 4.0.2a ActionColumn的使用
2011-07-10 23:50 9296ActionColumn是有问题的(不敢说是BUG),text ... -
Sencha SDK Tools 1.1的安装(Mac OS)
2011-06-08 21:06 4619安装其实十分简单,双击安装程序即可实现安装,底层貌似用到了Qt ... -
ExtJS 4.0 的改变(仅发表我发现的)
2011-05-25 17:23 10231最近写了一个较为完整版(有部分细节没说)的,去看看这里吧htt ... -
EXTJS3.0.3的本地资源包乱码的问题
2009-11-15 23:33 2279今天忽然看到首页上有3.0.3开放下载的消息,有点兴奋 ... -
EXTJS组件化(四)---减少你的代码
2009-11-11 02:14 4249代码量,BUG和维护成本是水涨船高的关系,这点应该不能被否认的 ... -
EXTJS组件化(三)----组件之间的暧昧关系
2009-10-17 01:52 6386我忽然发现,菜鸟更愿意与人分享他的学习成果. 在开发 ... -
EXTJS组件化(二)----简易的私有和公有
2009-09-25 21:03 3072我一直认为,凡是我已经了解的东西,国内必定已经有了一大 ... -
EXTJS组件化(一)----建立你的思想
2009-09-25 00:51 11225首先感谢朱治生朋友转载了我的帖子,由于种种不可抗的原因导致Do ...
相关推荐
网上有些这样的例子,但是下了几个都没有跑起来,哎,希望那些发文章的人要发就发全的,别发个半生不熟的。... 现在自己整理了一个Struts2+ExtJS2实现文异步文件上传,没法上传图片无法看到效果,直接上源码吧。
Extjs4文件上传,后台struts2
研究了半天的ExtJs+Struts2多文件上传.直接导入就可以运行。
1.extjs 的简单增删改。 2.后台使用struts2实现 3.左边是树形菜单。
@@@extjs+struts2+json plugin的例子
一个运用Extjs,Struts2, json,iterator技术构建的iterator_jsonDemo2。iterator_jsonDemo1的链接:http://download.csdn.net/detail/cafebar123/8816409 运用了Extjs,Struts2, json,iterator技术, 将数据从...
struts2 extjs 实现多图片批量上传,已经运用到项目当中了。
ExtJs + Struts2 + JSON 程序总结
eclipse下EXTJS4+STRUTS2+JAVA增删改查的完整例子
struts2+extjs3的单/多文件上传,后台也可以不用struts2,前台也可以去掉extjs,资源包含所需要的所有JAR包,无需另外下载,代码量绝对精简易懂。
extjs+struts2分页例子,简单明了,一看即可学会,还不赶快下载看看吧
Struts2与extjs整合例子
extjs,struts,spring项目代码 extjs,struts,spring项目代码 extjs,struts,spring项目代码
搭建EXTJS和STRUTS2框架(ext和struts2简单实例)
批量图片预览上传(extjs,支持html5和flash)
ExtJS与Struts2的整合工程实例,能成功部署的MyEclipse工程,还配有相应的文档。
EXTJS json struts2制作登陆窗口
应用extjs4和struts2开发的省市区三级联动完整示例,导入myeclipse即可用,无需再导入任何jar包
讲述 extjs 整合 struts hibernate sping 和extjs怎么和Highchart整合
Extjs例子Extjs例子Extjs例子Extjs例子Extjs例子