ext+struts2文件上传

EXTJS配合Struts2的图片上传
最近一直在用Struts2,忽然心血来潮想做个图片上传并预览的功能,这个功能我其实在Struts1里早就玩过了的,本来以为Struts2无非也就那么一回事,但是测试成功之后发现,过程还是颇具周折的.....
我是直接拷贝的工程里的代码,所以可能有一部分无关的代码,懒得去弄了
废话不多说,上例子代码:


首先,我们新建一个BaseAction,这个Action主要就是为了实现那两个接口,我就直接把我工程里的Copy过来:
Java代码
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");  
    }  
 


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代码
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;  
    }  


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代码
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();  
        }  
    };  


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代码
<?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>     

<?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代码
Ext.namespace("HRM.External.Image");  
/** 
* @author <a href="mailto:[email protected]">葛昊</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.namespace("HRM.External.Image");
/**
* @author <a href="mailto:[email protected]">葛昊</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代码
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 || {};  
        }  
    }  
}); 

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代码
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 : "例如[email protected]",  
                    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()  
    });  
})

你可能感兴趣的:(apache,json,struts,servlet,ext)