Extjs项目使用技巧————文件上传

在组件中的上传,上传注意一下内容:
1、 在上传时需要使用form.submit来上传文件;注意form对象时单独的,不能和其他表单一同使用;文件上传的发送post请求在debug中无法看到,只能在网络中查看到
在js文件中的上传步骤:
1、获得form对象,利用该对象来上传文件;
2、获得上传的form表单;利用该表单来获取文件名称
3、获得文件名;
                   
                    xtype : "form",
                    idFlag:'fileForm',
                    layout : "form",
                    labelWidth : 60,
                    fileUpload : true,
                    style : 'margin:0px 0px 0px 20px',
                    items : [{
                        anchor : "95%",
                        name : "upload",
                        buttonText : '',
                        appendixId : '',// 对于谷歌上传增加的Id by liyanshuai 2011-08-10
                        emptyText: '请选择图片',
                        fieldLabel : '上传图片',
                        buttonCfg: {iconCls: 'upload'},
                        xtype : 'fileuploadfield',
                        appendixUrl : "/customer/agreement/agree-sub!saveAppendix.action",
                        idFlag : "uploadjpg",
                        listeners: {
                            fileselected : function() {
                                //获得上传的文件名
                                var val = this.fileInput.dom.value;
                                //获取表单对象
                                var appendix = tempthis.find( "idFlag" , "uploadjpg" ) [0];
                                //获取后缀名称
                                var isImage = val.substring(val.lastIndexOf("."));
                                //判断是否为图片
                                if(isImage.toLowerCase() ==".jpg" || isImage.toLowerCase()==".gif" || isImage.toLowerCase()==".bmp" || isImage.toLowerCase()==".png"){
                                    appendix.clearInvalid();
                                    //调用文件上传
                                    tempthis.saveAppendix();
                                }else{
                                    appendix.markInvalid('请选择正确的图片格式!')
                                    Ext.ux.LevitationMsgBox.msg('提示','请选择正确的图片格式!');
                                  }
                            }
                        }
                    }]
  saveAppendix()方法使用

文件上传时发送的参数:



       saveAppendix : function() {
        var tempthis = this;
        // 文件上次的form对象
          var thisForm = tempthis.find('idFlag','fileForm')[0];
          var appendix = tempthis.find( "idFlag" , "uploadjpg" ) [0];
          //谷歌浏览器情况下需要加下appendixId的参数这样后台才能保存附件 by liyanshuai 2011-08-10
          var uploadName = appendix.getValue();
          var index = uploadName.lastIndexOf("\\");
          var params = {},
          //获得文件名称
          uploadName = uploadName.substring(index+1,uploadName.length);
          //appendixObj用来向后台发送数据的对象,存放着文件名等信息
               if(!tempthis.appendixObj) {//不为空表示第一次上传
                var fileName = tempthis.find("idFlag","uploadjpg")[0].getValue();
                var uploadName = fileName;
                if(fileName.indexOf("\\")>0) {
                    var index = fileName.lastIndexOf("\\");
                    uploadName = fileName.substring(index+1,fileName.length);
                }
                //将文件等信息转换为json数据,发送到后台,用于转化为Appendix对象
                tempthis.appendixObj = "{'appendixName':'"+tempthis.find("idFlag","uploadjpg")[0].getValue()+
                "','appendixTypeName':'"+tempthis.find("idFlag","uploadjpg")[0].getValue().substring(tempthis.find("idFlag","uploadjpg")[0].getValue().lastIndexOf(".")+1)+
                "','appendixTypeCode':'"+tempthis.find("idFlag","uploadjpg")[0].getValue().substring(tempthis.find("idFlag","uploadjpg")[0].getValue().lastIndexOf(".")+1)+"'}";
            }
            var fileName = tempthis.find("idFlag","uploadjpg")[0].getValue();
            var uploadName = fileName;
            if(fileName.indexOf("\\")>0) {
                var index = fileName.lastIndexOf("\\");
                uploadName = fileName.substring(index+1,fileName.length);
            }
            //上传文件的文件名
            tempthis.thisAppendixName = uploadName;
       
          if(uploadName){
              Ext.apply(params,{
                  //增加的参数 appendixId by liyanshuai 2011-08-10
                 appendixId : appendix.appendixId,
                 uploadFileName : uploadName,
                 uploadContentType : uploadName.substring(uploadName.lastIndexOf(".")+1,uploadName.length),
                 appendixObj : tempthis.appendixObj
             });
          }
          Ext.MessageBox.show( {
            title : "提示",
            msg : "正在保存,请稍后...",
            progress : true,
            width : 300,
            wait : true,
            closable : false
        } );
        //进行保存上传文件
         thisForm.getForm().submit( {
            url : "/customer/agreement/agree-sub!deleteAndSaveAppendix.action",
            params : params,
            success : function (form,action){
                   var resultTrue = Ext.util.JSON.decode(action.response.responseText);
                   tempthis.appendixObj = Ext.encode(resultTrue);
                   tempthis.isDelApp = true;
                Ext.MessageBox.hide();
                Ext.ux.LevitationMsgBox.msg( "提示" , "保存成功!" );
            },
            failure : function ( response , opts ){
                Ext.MessageBox.hide();
                Ext.ux.LevitationMsgBox.msg( "提示" , "数据提交错误!" );
            }
        } )
      },
          //当点击取消或者重置的时候删除以前上传附件
    immediatelyDeleteApp : function(tempthis) {
        if(!tempthis.isDelApp) {
            //标识位update是修改时的hide不做删除操作
            Ext.Ajax.request({
                url: '/customer/agreement/agree-sub!immediatelyDeleteAppdendix.action',
                params : {
                       thisAppendixName:tempthis.thisAppendixName,
                       appendixObj : tempthis.appendixObj
               },  
               success: function(response, opts) {
                       tempthis.appendixObj = "";
               },
               failure: function(response, opts) {
                       
               }
            });
        }
    }
后台代码:
/**
     * 对于谷歌情况下上传附件的方法
     * @Date Aug 10, 2011
     * @author zhangwb
     * @throws IOException
     * 
     */

    public void deleteAndSaveAppendix() throws Exception{
        //文件上传是注意上传需要进行语言进行更改
        ServletActionContext.getResponse().setContentType(
        "text/html;charset=utf-8;");
        //upload是文件需要判断文件的大小
        if (upload != null && upload.length() > MAXUPLOADFILESIZE) {
            String errorMsg = "上传的文件过大,允许上传的图片最大为:10M!";
            Struts2Utils.getResponse().getWriter().write(
                    "{'success':false, 'errorMsg':'" + errorMsg + "'}");
            return;
        }
        //存储着文件的相关信息如文件名称,格式等信息,将js文件中上传的文件信息转化为对象
        Appendix appendix = null;
        if (appendixObj != null && !"".equals(appendixObj)) {
            appendix = JsonUtils.json2Bean(this.appendixObj, new Appendix());
        }
        //获得要上传的文件路径
        String path = ServletActionContext.getServletContext().getRealPath(
                File.separator+"upload"+File.separator+"agreement");
        // 获得一个附件对象返回给前台
        Appendix returnappendix = this.appendixManager.deleteAndSaveAppendix(
                this.upload, appendix, path, this.isDeleteApp,
                this.uploadFileName);
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[] { "hibernateLazyInitializer",
                "handler" });
        jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
                new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss"));
        StringBuffer sb = new StringBuffer();
        StringBuffer strSb = new StringBuffer(JSONSerializer.toJSON(
                returnappendix, jsonConfig).toString());
        strSb.deleteCharAt(0);
        sb.append("{'success':true,");
        sb.append(strSb.toString());
        Struts2Utils.getResponse().getWriter().write(sb.toString());
    }
  deleteAndSaveAppendix是组件里面的方法直接调用          
实体类如何配置
// 上传附件表集合
    private Set<Appendix> appendix = new HashSet<Appendix>();
        /**
     * @return the appendix 建立产品表与附件表多对多关联
     */

    @ManyToMany
    @JoinTable(name = "OBJECT_APPENDIX_RELATION", joinColumns = { @JoinColumn(name = "OBJECT_ID") }, inverseJoinColumns = { @JoinColumn(name = "APPENDIX_ID") })
    @Fetch(FetchMode.SUBSELECT)
    public Set<Appendix> getAppendix() {
        return appendix;
    }
    public void setAppendix(Set<Appendix> appendix) {
        this.appendix = appendix;
    }




posted @ 2013-11-19 11:36  thero  阅读(1859)  评论(0编辑  收藏  举报