struts2+extjs文件上傳完整實現(解決了上傳中的各種問題)

jopen 10年前發布 | 112K 次閱讀 Struts2 Web框架

首先需要引入上傳控件

<script type="text/javascript" src="<%=basePath%>/js/ext/examples/ux/fileuploadfield/FileUploadField.js" charset="utf-8"></script>

彈出上傳框對應extjs代碼

    var uploadForm=new Ext.FormPanel({  
        id:'uploadForm',  
        width:520,  
        frame:true,  
        fileUpload: true,    
        autoHeight:true,  
        bodyStyle:'10px 10px 0px 10px',  
        labelWidth:50,  
        enctype: 'multipart/form-data',   
        defaults:{  
            anchor: '95%',  
            allowBlank: false  
        },  
        items:[  
            {  
                xtype:'fileuploadfield',  
                emptyText: '請選擇上傳文件...',   
                fieldLabel: '文件:',   
                id:'uploadFile',  
                name: 'upload',   
                allowBlank: false,     
                blankText: '文件名稱不能為空.',     
                 buttonCfg: {  
                            text: '選擇...'// 上傳文件時的本地查找按鈕  
                  }  
            }  
        ],  
        buttons: [{  
                        text: '上傳',  
                        handler: function(){  
                            if(uploadForm.getForm().isValid()){  
                                uploadForm.getForm().submit({  
                                    url:basePath+ '/documentManage/upload_upload.action',  
                                    method:'POST',  
                                    waitTitle: '請稍后',  
                                    waitMsg: '正在上傳文檔文件 ...',  
                                    success: function(fp, action){  
                                        Ext.MessageBox.alert('信息', action.result.msg);    
                                        Ext.getCmp("uploadFile").reset();          // 指定文件字段的id清空其內容  
                                        addwin.hide();  
                                        grid.store.load({params:{start : 0,limit : combo.value}});  
                                    },  
                                    failure: function(fp, action){  
                                        Ext.MessageBox.alert('警告', action.result.msg);    
                                        addwin.hide();  
                                    }  
                                });  
                            }  
                        }  
                    },{  
                        text: '重置',  
                        handler: function(){  
                            uploadForm.getForm().reset();  
                        }  
                    }]  

    });  

    addwin = new Ext.Window({  
        title : '上傳新文檔',  
        closable : true,  
        width : 520,  
        autoHeight: true,  
        border : false,  
        plain : true,  
        modal : true,  
        layout : 'fit',  
        bodyStyle : 'padding:5px;',  
        maximizable : false,// 禁止最大化  
        closeAction : 'hide',  
        closable : true,// 是否有關閉  
        collapsible : true,// 可折疊  
        iconCls : 'bind',  
        items : [uploadForm]  
    });  




struts2 action代碼
    package cn.com.action;  

    import java.io.BufferedInputStream;  
    import java.io.BufferedOutputStream;  
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  

    import javax.servlet.http.HttpServletResponse;  

    import org.apache.struts2.ServletActionContext;  

    import cn.com.css.common.action.BaseAction;  


    public class FileUploadAction extends BaseAction {  

        private static final long serialVersionUID = 5156288255337069381L;  

        private  String msg;  
        private String contentType;  
        private File docmentFile;  
        private String fileName;  


        public String upload() throws Exception {  
            String realPath = "E:\\" + fileName;  
            if (docmentFile.isFile()) {  
                BufferedInputStream bis = new BufferedInputStream(  
                        new FileInputStream(docmentFile));  
                BufferedOutputStream bos = null;  
                try {  
                    bos = new BufferedOutputStream(new FileOutputStream(realPath));// 為以防萬一,以后寫文件的路徑盡量寫成正雙斜杠的  
                    // 從源文件中取數據,寫到目標文件中  
                    byte[] buff = new byte[8192];  
                    for (int len = -1; (len = bis.read(buff)) != -1;) {  
                        bos.write(buff, 0, len);  
                    }  
                    bos.flush();  
                } catch (IOException ie) {  
                    ie.printStackTrace();  
                    msg="文件上傳失敗";  
                    HttpServletResponse response = ServletActionContext.getResponse();  
                    response.setContentType("text/html;charset=UTF-8");  
                    return "none";  
                } finally {  
                    if (bis != null) {  
                        try {  
                            bis.close();  
                        } catch (IOException ie) {  
                            ie.printStackTrace();  
                        }  
                    }  
                    if (bos != null) {  
                        try {  
                            bos.close();  
                        } catch (IOException ie) {  
                            ie.printStackTrace();  
                        }  
                    }  
                }  
            }  
            msg="文件上傳成功";  
            HttpServletResponse response = ServletActionContext.getResponse();  
            response.setContentType("text/html;charset=UTF-8");  
            return "none";  
        }  

        public String getFileName() {  
            return fileName;  
        }  

        public void setFileName(String fileName) {  
            this.fileName = fileName;  
        }  

        // since we are using <s:file name="upload" .../> the file name will be  
        // obtained through getter/setter of <file-tag-name>FileName  
        public String getUploadFileName() {  
            return fileName;  
        }  

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

        // since we are using <s:file name="upload" ... /> the content type will be  
        // obtained through getter/setter of <file-tag-name>ContentType  
        public String getUploadContentType() {  
            return contentType;  
        }  

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

        // since we are using <s:file name="upload" ... /> the File itself will be  
        // obtained through getter/setter of <file-tag-name>  
        public File getUpload() {  
            return docmentFile;  
        }  

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

        public String getMsg() {  
            return msg;  
        }  

        public void setMsg(String msg) {  
            this.msg = msg;  
        }  

        public String getContentType() {  
            return contentType;  
        }  

        public void setContentType(String contentType) {  
            this.contentType = contentType;  
        }  

        public File getDocmentFile() {  
            return docmentFile;  
        }  

        public void setDocmentFile(File docmentFile) {  
            this.docmentFile = docmentFile;  
        }  

    }  



struts.xml配置:
<?xml version="1.0" encoding="utf-8"?>  
<!DOCTYPE struts PUBLIC  
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd">  
<struts>  
    <package name="documentManage" namespace="/documentManage"  
        extends="global-struts-default">  

        <action name="upload_*"  
            class="cn.com.FileUploadAction"  
            method="{1}">  
            <result type="json" name="none">  
                <param name="contentType">text/html;charset=utf-8</param>  
                <param name="excludeProperties">  
                    user.myQuestionses,user.messages,user.myNotes,user.taskPapers,  
                    user.tasks,user.testPapers,user.articles  
                </param>  
            </result>  
        </action>  
    </package>  
</struts>  
 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!