extjs上传excel文件表单formpanel完整案例,首先弹出一个框,里面有一个extjs form表单,点击按钮可以选择文件,然后点击确定按钮提交表单到服务器,服务器接收代码以接收处理excel文件为例。
1.extjs客户端上传文件表单formpanel代码:
var uploadWin=new Ext.Window({ modal :true, title:"批量导入记录", width:400, id:"uploadFileWin", height:230, bodyBorder:false, layout:"fit", bodyStyle:"background-color:#FFF", items:[{ border:false, id:"uploadForm", xtype:"form", fileUpload: true , style:"padding-top:50px;", items:[{ xtype:'textfield', inputType:'file', id:"uploadFileTextF", name:'uploadFile', labelStyle : 'text-align:right;font-weight:bold', allowBlank: false , fieldLabel:'选择文件*' }] }], buttonAlign:"center", buttons:[{ text:"确定", handler:function(){ var form=Ext.getCmp("uploadForm").form; var fileName=Ext.getCmp("uploadFileTextF").getValue(); fileName=fileName.split('.'); fileName=fileName[fileName.length-1]; if(fileName!="xls"&&fileName!="xlsx"){ Ext.Msg.alert("系统提示", "必须选择Microsoft Office Excel 工作表!"); return false; } if (form.isValid()){ form.submit({ method:'post', url:'/doAction?Action=importRecord', // 根据自己系统的需要调用程序处理上传文件 24 waitMsg:'文件上传中...', success: function (form,action) { //alert(action.msg); Ext.Msg.alert("系统提示", action.result.msg); mygrid.store.reload(); Ext.getCmp("uploadFileWin").close(); }, failure: function (form,action) { Ext.Msg.alert("系统提示", action.result.msg); } }); } else { Ext.Msg.alert("系统提示","请选择文件后再上传!"); } } }] }); uploadWin.show();
2.java接收文件servlet代码:
int maxPostSize = 1000 * 1024 * 1024; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(maxPostSize); List fileItems = servletFileUpload.parseRequest(req); Iterator iter = fileItems.iterator(); JSONObject returnJson=new JSONObject(); int countRecord=0; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) {// 是文件 Workbook book = Workbook.getWorkbook( item.getInputStream()) ; Sheet sheet = book.getSheet(0); int rows = sheet.getRows(); String fieldsStr="sname,pname,idcardNo,traincardno,serid"; String returnStr=""; for(int i = 0; i < rows; i++) { Cell [] cell = sheet.getRow(i); String valuesStr=""; countRecord++; for(int j=0; j<cell.length; j++) { if(!sheet.getCell(0, i).getContents().equals("")){ if(i>=1){ valuesStr+="'"+sheet.getCell(j, i).getContents()+"'"; } } } } } book.close(); returnJson.put("success", true); returnJson.put("msg", "导入成功,共上传"+countRecord+"条记录。"); }else{ returnJson.put("success", false); returnJson.put("msg", "请上传excel文件!"); } } out.print(returnJson.toString());