打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
ExtJS之上传文件示例【struts2方式】

今天突然想起来以前的关于EXT的上传的文章没有贴出来,现在贴出代码在此

Js代码
 
  1. <SPAN style="FONT-SIZE: medium">var uploadForm= new Ext.FormPanel({   
  2.                 id: 'form-panel',   
  3.                 fileUpload: true,   
  4.                 width: 500,   
  5.                 frame: true,   
  6.                 //title: '流程文件上传',   
  7.                 collapsible:true,   
  8.                 autoHeight: true,   
  9.                 bodyStyle: 'padding: 10px 10px 0 10px;',   
  10.                 labelWidth: 50,   
  11.                 defaults: {   
  12.                     anchor: '95%',   
  13.                     allowBlank: false,   
  14.                     msgTarget: 'side'  
  15.                 },   
  16.                 items: [{   
  17.                     xtype:'combo',   
  18.                     width : 200,   
  19.                     allowBlank : false,   
  20.                     blankText : '必须选择文档类型',   
  21.                     hiddenName : 'CId'//这个hiddenName指的就是BookTypeId   
  22.                     name : 'CName',   
  23.                     store : new Ext.data.Store({   
  24.                         autoLoad :true,   
  25.                          reader: new Ext.data.JsonReader({//读取json数据      
  26.                                 root:'TCategoryList',                        //      
  27.                                 totalProperty:'totalProperty',  //总记录数      
  28.                                 id:'CId'                       
  29.                              },   
  30.                         Ext.data.Record.create([   
  31.                             {name: 'CId'},   
  32.                             {name: 'CName'}   
  33.                         ])   
  34.                         ),   
  35.                         proxy : new Ext.data.HttpProxy({   
  36.                             url : path+'doc/getTCategoryForDoc.action'  
  37.                         })   
  38.                     }),//设置数据源   
  39.                     allQuery:'alldoc',//查询全部信息的查询字符串   
  40.                     triggerAction: 'all',//单击触发按钮显示全部数据   
  41.                     editable : false,//禁止编辑   
  42.                     loadingText : '正在加载文档类型信息',//加载数据时显示的提示信息   
  43.                     displayField:'CName',//定义要显示的字段   
  44.                     valueField : 'CId',   
  45.                     emptyText :'请选择文档类型',   
  46.                     mode: 'remote',//远程模式   
  47.                     id:'CName',   
  48.                     fieldLabel:'类型'  
  49.                 },{   
  50.                     xtype: 'fileuploadfield',   
  51.                     id: 'form-file',   
  52.                     emptyText: '请选择流程文件...',   
  53.                     fieldLabel: '文件',   
  54.                     name: 'upload',     // ★ from字段,对应后台java的bean属性,上传的文件字段   
  55.                     buttonCfg: {   
  56.                         text: '',  // 上传文件时的本地查找按钮   
  57.                         iconCls: 'icon-upload'  // 按钮上的图片,定义在CSS中   
  58.                     }   
  59.                 },   
  60.                 {   
  61.                         xtype: 'hidden',   
  62.                         id: 'fileName',   
  63.                         emptyText: '请选择文档文件...',   
  64.                         name: 'fileName',   
  65.                         text:Ext.getCmp("form-file"//在上传这个框中,getCmp可以获取整条路径的最后的名称   
  66.                            
  67.                   },   
  68.                   {   
  69.                        xtype:'hidden',   
  70.                        name : 'docId',   
  71.                        id:'docId'  
  72.                    }   
  73.                ],   
  74.                 buttons: [{   
  75.                     text: '上传',   
  76.                     handler: function(){   
  77.                        
  78.                         if(uploadForm.getForm().isValid()){   
  79.                             uploadForm.getForm().submit({   
  80.                                 url:path+ 'upload/upload.action?Tab_staffId='+staffId,   
  81.                                 method:'POST',   
  82.                                 waitTitle: '请稍后',   
  83.                                 waitMsg: '正在上传文档文件 ...',   
  84.                                 success: function(fp, action){   
  85.                                 updatedocListForUpload(action.result.docId,action.result.name,action.result.docUrl,action.result.CName,action.result.extType,action.result.state);   
  86.                                    msg('成功!''文档文件上传成功!');   
  87.                                    //msg("返回的ID呢"+action.result.docId);                                   
  88.                                     //Ext.log('上传成功。')   
  89.                                     //Ext.log(action.failure)   
  90.                                     //failure   
  91.                                     //Ext.log(action.result.upload);   
  92.                                     //Ext.log(action.result.msg);          
  93.                                     Ext.getCmp("form-file").reset();          // 指定文件字段的id清空其内容   
  94.                                     Ext.getCmp("CName").reset();   
  95.                                 },   
  96.                                 failure: function(fp, action){   
  97.                                     msg('失败!''文档文件上传失败!');   
  98.                                 }   
  99.                             });   
  100.                         }   
  101.                     }   
  102.                 },{   
  103.                     text: '重置',   
  104.                     handler: function(){   
  105.                     uploadForm.getForm().reset();   
  106.                     }   
  107.                 }]   
  108.             });</SPAN>  

  具体处理的ACTION

Java代码
 
  1. <SPAN style="FONT-SIZE: medium">package lsbpm.web.action;   
  2.   
  3. import java.io.BufferedInputStream;   
  4. import java.io.BufferedOutputStream;   
  5. import java.io.File;   
  6. import java.io.FileInputStream;   
  7. import java.io.FileOutputStream;   
  8. import java.io.IOException;   
  9. import java.net.URLEncoder;   
  10. import java.sql.Timestamp;   
  11. import java.util.ArrayList;   
  12. import java.util.HashMap;   
  13. import java.util.List;   
  14. import java.util.UUID;   
  15.   
  16. import lsbpm.db.domain2.TCategory;   
  17. import lsbpm.db.domain2.TDoc;   
  18. import lsbpm.db.domain2.TDocCategory;   
  19. import lsbpm.db.domain2.TStaff;   
  20. import lsbpm.web.lecene.LuceneIndex;   
  21. import net.sf.json.JSONObject;   
  22.   
  23. import org.apache.struts2.ServletActionContext;   
  24.   
  25. /**  
  26.  * Show case File Upload example's action. <code>FileUploadAction</code>  
  27.  */  
  28. public class FileUploadAction extends BaseAction {   
  29.   
  30.     private static final long serialVersionUID = 5156288255337069381L;   
  31.   
  32.     private String contentType;   
  33.     private File upload;   
  34.     private String fileName;   
  35.     private String caption;   
  36.     private String CId;//文档TCategory的ID   
  37.     private String jsonMsg;// 返回ExtJs upload form消息   
  38.     private String Tab_staffId;   
  39.     public String getJsonMsg() {   
  40.         return jsonMsg;   
  41.     }   
  42.   
  43.     public void setJsonMsg(String jsonMsg) {   
  44.         this.jsonMsg = jsonMsg;   
  45.     }   
  46.   
  47.     // since we are using <s:file name="upload" .../> the file name will be   
  48.     // obtained through getter/setter of <file-tag-name>FileName   
  49.     public String getUploadFileName() {   
  50.         return fileName;   
  51.     }   
  52.   
  53.     public void setUploadFileName(String fileName) {   
  54.         this.fileName = fileName;   
  55.     }   
  56.   
  57.     // since we are using <s:file name="upload" ... /> the content type will be   
  58.     // obtained through getter/setter of <file-tag-name>ContentType   
  59.     public String getUploadContentType() {   
  60.         return contentType;   
  61.     }   
  62.   
  63.     public void setUploadContentType(String contentType) {   
  64.         this.contentType = contentType;   
  65.     }   
  66.   
  67.     // since we are using <s:file name="upload" ... /> the File itself will be   
  68.     // obtained through getter/setter of <file-tag-name>   
  69.     public File getUpload() {   
  70.         return upload;   
  71.     }   
  72.   
  73.     public void setUpload(File upload) {   
  74.         this.upload = upload;   
  75.     }   
  76.   
  77.     public String getCaption() {   
  78.         return caption;   
  79.     }   
  80.   
  81.     public void setCaption(String caption) {   
  82.         this.caption = caption;   
  83.     }   
  84.   
  85.     // 解析上传的流程文件,将流程图分解后存入数据库中   
  86.     // 用json格式返回成功失败及错误信息等,可直接与ExtJS衔接。   
  87.        
  88.     public String combinStr(String str,int i){   
  89.         str=str.substring(0,str.indexOf("."))+i+ str.substring(str.indexOf("."));   
  90.         return str;   
  91.     }   
  92.        
  93.     public String upload() throws Exception {   
  94.         System.out.println("执行上传文件操作。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。");   
  95.         // 定义要返回的对象,返回时用json包装   
  96.         HashMap<String, String> retMsg = new HashMap<String, String>();   
  97.         TStaff staff=(TStaff)genericService.findById(TStaff.class, Tab_staffId);   
  98.         TCategory category=(TCategory)genericService.findById(TCategory.class, CId);   
  99.         TDoc doc = new TDoc();   
  100.         doc.setName(fileName);//-------------------------------------------------(1)filename属性(非空)   
  101.         System.out.println("拼装前------------------>"+fileName);   
  102.         List<String> propertisList=new ArrayList<String>();   
  103.         propertisList.add("docVersion-");        
  104.         List<TDoc> result=genericService.findByProperty(doc, propertisList, 00);   
  105.         doc.setDocVersion(1);//-------------------------------------------------(2)DocVersion属性(非空)   
  106.         int size=propertisList==null?0:result.size();   
  107.         if(size>0){   
  108.            int docVersion=result.get(0).getDocVersion();   
  109.            doc.setDocVersion(docVersion+1);   
  110.            fileName=combinStr(fileName,docVersion+1);////主要针对相同名称的文件处理加上版本号   
  111.            System.out.println("--------------------经过版本升级---------------------------------");   
  112.         }   
  113.         doc.setDocAlias(fileName);//-------------------------------------------------(3)DocAlias属性(非空)   
  114.         doc.setBoost(0d);//-------------------------------------------------(4)Broost属性(非空)   
  115.         System.out.println("拼装后----------------->"+fileName);   
  116.         String realPath="E:\\DataDir\\"+fileName;   
  117.         if (upload.isFile()) {   
  118.             BufferedInputStream bis = new BufferedInputStream(   
  119.                     new FileInputStream(upload));   
  120.             BufferedOutputStream bos = null;   
  121.             try {   
  122.                 bos = new BufferedOutputStream(new FileOutputStream(realPath));//为以防万一,以后写文件的路径尽量写成正双斜杠的   
  123.                 // 从源文件中取数据,写到目标文件中   
  124.                 byte[] buff = new byte[8192];   
  125.                 for (int len = -1; (len = bis.read(buff)) != -1;) {   
  126.                     bos.write(buff, 0, len);   
  127.                 }   
  128.                 bos.flush();   
  129.             } catch (IOException ie) {   
  130.                 ie.printStackTrace();   
  131.             } finally {   
  132.                 if (bis != null) {   
  133.                     try {   
  134.                         bis.close();   
  135.                     } catch (IOException ie) {   
  136.                         ie.printStackTrace();   
  137.                     }   
  138.                 }   
  139.                 if (bos != null) {   
  140.                     try {   
  141.                         bos.close();   
  142.                     } catch (IOException ie) {   
  143.                         ie.printStackTrace();   
  144.                     }   
  145.                 }   
  146.             }   
  147.                
  148.               
  149.             System.out.println("----------------------------0000");   
  150.             doc.setDocUrl(fileName);//-------------------------------------------------(5)DocUrl属性(非空)         
  151.             doc.setExtType(fileName.substring(fileName.lastIndexOf('.')+1));//---------(6)extType属性(非空)               
  152.             doc.setState("可用");//状态这个暂时写死为可用 //----------------------------------(7)state属性(非空)   
  153.             doc.setTStaffByDesigner(staff);//设计者先和操作者暂定为同一人-------------------- (8)designer属性(可空)   
  154.             doc.setTStaffByOperator(staff);//------------------------------------------(9)operator属性(非空)   
  155.             doc.setUpgradeDate(new Timestamp(System.currentTimeMillis()));   
  156.             boolean isSuccess = false;   
  157.             System.out.println("即将要插入数据库的文件内容为:"+doc);   
  158.             genericService.create(doc);   
  159.                
  160.             //插入文档类型   
  161.             TDocCategory cate=new TDocCategory();   
  162.             cate.setTCategory(category);   
  163.             cate.setTDoc(doc);   
  164.             cate.setBoost(0d);   
  165.             genericService.create(cate);   
  166.                
  167.                
  168.             String Id = doc.getDocId();   
  169.             System.out.println("新增后获取到的员工ID" + Id);        
  170.             System.out.println(fileName + "----------------");   
  171.                
  172.             String extTypes=doc.getExtType();      
  173.             //如果上传的文件在我要建立索引的范围之内,可以见索引,否则不建立   
  174.             if(extTypes.equals("pdf")||extTypes.equals("html")||   
  175.                 extTypes.equals("rtf")||extTypes.equals("doc")||   
  176.                 extTypes.equals("ppt")||extTypes.equals("xls")||   
  177.                 extTypes.equals("txt")){   
  178.              LuceneIndex index=new LuceneIndex();//建立索引   
  179.              index.buildsingle(doc);   
  180.              System.out.println("索引完毕。。。。。。。。。。。。。。。。。。。。。");   
  181.             }   
  182.               
  183.             // 流程文件解析和加载,成功! 将流打到客户端   
  184.             retMsg.put("success""true");   
  185.             retMsg.put("docId", Id);   
  186.             retMsg.put("name", doc.getDocAlias());   
  187.             if(doc.getTDocCategories().size()==1){   
  188.                  for(TDocCategory cate1:doc.getTDocCategories()){   
  189.                      retMsg.put("CName",cate1.getTCategory().getName());   
  190.                  }   
  191.             }   
  192.             retMsg.put("extType", doc.getExtType());   
  193.             retMsg.put("state", doc.getState());   
  194.             retMsg.put("docId", doc.getDocId());   
  195.             retMsg.put("docUrl", doc.getDocUrl());   
  196.             retMsg.put("upload""ok");   
  197.             retMsg.put("msg""hhaahhaa!!");   
  198.   
  199.         } else {   
  200.             // 流程文件解析和加载,失败!   
  201.             retMsg.put("failure""true");   
  202.             retMsg.put("upload""error");   
  203.             retMsg.put("msg"" failed !!");   
  204.   
  205.         }   
  206.   
  207.         // json包装返回对象   
  208.         jsonMsg = JSONObject.fromObject(retMsg).toString();   
  209.         return SUCCESS;   
  210.     }   
  211.   
  212.     public String getFileName() {   
  213.         return fileName;   
  214.     }   
  215.   
  216.     public void setFileName(String fileName) {   
  217.         this.fileName = fileName;   
  218.     }   
  219.   
  220.     public String getCId() {   
  221.         return CId;   
  222.     }   
  223.   
  224.     public void setCId(String cId) {   
  225.         CId = cId;   
  226.     }   
  227.   
  228.     public String getTab_staffId() {   
  229.         return Tab_staffId;   
  230.     }   
  231.   
  232.     public void setTab_staffId(String tabStaffId) {   
  233.         Tab_staffId = tabStaffId;   
  234.     }   
  235.        
  236.        
  237.   
  238. }   
  239. </SPAN>  

 struts.xml中添加一行代码

   <!-- 该属性指定Struts 2文件上传中整个请求内容允许的最大字节数 -->
 <constant name="struts.multipart.maxSize" value="102400000000000" />

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Struts文件上传
主题:基于kindeditor3.4的上传功能的JAVA实现(好)
CKEditor图片上传实现详细步骤(使用Struts 2)
文件上传:SmartUpload和FileUpload
jQuery上传插件Uploadify 3.2 上传文件
struts2 文件上传示例1_普通上传
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服