* Ext上传:
ext文件上传需要扩展控件的支持:
<form id="uploadFileForm" action="" method="post" enctype="multipart/form-data">
   <div id="fileupload" style="cursor:hand;"></div>
</form>
1 前台js代码
var uploadForm = new Ext.BasicForm('uploadFileForm');

var fileUploadBt = new Ext.ux.form.FileUploadField({
   renderTo: 'fileupload',        
   buttonOnly: true,
   buttonText: 'Excel导入',
   buttonCfg: {
       iconCls: 'download'
       //tooltip: '从Excel导入物料信息'
   },
   listeners: {
       'fileselected': function(fb, v){
       //v 为文件路径
       if(fac.getValue() == ''){
           Ext.Msg.alert('操作提示', '请先选择一个成本中心或填写内部订单号!');
           fb.reset();
       }else{
           indexFun.addMarcFromExcel(v);
       }
       }
   }
});
uploadForm.add(fileUploadBt);

addMarcFromExcel :function(filePath){
   uploadForm.submit({
       fileUpload: true,
       standardSubmit: true,
       url: '<c:out value="${path}" />/purchaseApply.htm?method=parseExcel',
       params: {
       costCenter: costCenter.getValue(),
       factNo: costCenterCmbStore.getAt(costCenterCmbStore.find('costNo',costCenter.getValue())).get('factNo'),
       internalOrder: internalOrder.getValue()
       },
       waitMsg: '文件上传中,请等待...',    
       waitTitle: '上传进度条',
       success: function(form,action){            
       yyExt.info('导入成功', msgContent);
       for(var i=0;i<action.result.prdArr.length;i++){
           indexFun.insertMarcToGrid(action.result.prdArr[i]);
       }
       form.reset();
       },
       failure: function(form, action) {
       form.reset();
       switch (action.failureType) {
           case Ext.form.Action.CLIENT_INVALID:
           Ext.Msg.alert('导入失败', 'Form fields may not be submitted with invalid values');
           break;
           case Ext.form.Action.CONNECT_FAILURE:
           Ext.Msg.alert('导入失败', 'Ajax communication failed');
           break;
           case Ext.form.Action.SERVER_INVALID:
              Ext.Msg.alert('导入失败', action.result.msg);
          }
       }
   });
}

2 后台java代码:
/**
* org.apache.commons.fileupload.servlet.ServletFileUpload
* 采用apache的ServletFileUpload解析request中的文件,并将文件相关信息封装进一个FileBean对象
*/
FileUploadUtil fileTool = new FileUploadUtil();
fileTool.setServletFileUpload(this.getServletFileUpload());
fileTool.setSizeMax(this.getFileMaxSize());
fileTool.init(request);
fileTool.setSaveFile(false); //上传的文件不保存到硬盘
FileBean fileBean = fileTool.saveFile();
/*
* 提取其他参数
*/
String costCenter = fileTool.getParameter("costCenter"); //成本中心
String factNo = fileTool.getParameter("factNo"); //工厂编号
String internalOrder = fileTool.getParameter("internalOrder"); //内部订单


* Ext下载:Ext没有对下载做任何处理,下载采用一般方式即可。
采用form提交方式:
<form  id="queryForm" target="myframe" method="post">
   <input type="text" id="marcNo" name="marcNo" style="width: 180px;">
   <input type="text" id="marcName" name="marcName" style="width: 100px">
</form>
//导出物料信息
download: function(){
   $("queryForm").action = "<c:out value="${path}"/>/marcInfo.htm?method=download";
   $("queryForm").submit();
}
后台java代码:
public ModelAndView download(HttpServletRequest request,HttpServletResponse response) throws Exception{
       response.setCharacterEncoding(this.DEFAULT_ENCODE);
       //取得输出流
       OutputStream out = response.getOutputStream();
       //清空输出流
       response.reset();
   try {
   /**
    * 1 提取条件参数
    */
   String marcNo = RequestUtil.getParameter(request, "marcNo", null); //物料编码
   String marcName = RequestUtil.getParameter(request, "marcName", null); //品名

   //设置响应头和下载保存的文件名
   response.setHeader("Content-Type","text/html; charset=UTF-8");
   response.setHeader("content-disposition","p_w_upload;filename="+excelModel.getPath());
   //定义输出类型
   response.setContentType("APPLICATION/msexcel");  
   /**
    * 2 根据条件参数得到相关文件的输出流,将输出流写回前台
    */

   } catch (Exception e) {
       log.error("下载物料信息出错:"+e.getMessage());
   }finally{
       out.close();
       out.flush();
   }
   return new ModelAndView(this.indexView,"sessionUserName",super.getSessionUser(request).getUserName());
}



*************************************************************************************

/*
*
* This file is part of Ext JS 4
*
* Copyright (c) 2011 Sencha Inc
*
*
* GNU General Public License Usage This file may be used under the terms of the
* GNU General Public License version 3.0 as published by the Free Software
* Foundation and appearing in the file LICENSE included in the packaging of
* this file. Please review the following information to ensure the GNU General
* Public License version 3.0 requirements will be met:
*
* If you are unsure which license is appropriate for your use, please contact
* the sales department at http://www.sencha.com/contact.
*
*/
Ext.require([ 'Ext.form.field.File' , 'Ext.form.Panel' , 'Ext.window.MessageBox' ]);
Ext.onReady(function() {
Ext.define( 'State' , {
extend : 'Ext.data.Model' ,
autoLoad : false ,
fields : [{
type : 'string' ,
name : 'text'
}, {
type : 'string' ,
name : 'flag'
}]
});
var store = Ext.create( 'Ext.data.Store' , {
model : "State" ,
proxy : {
type : "ajax" ,
url : "./totosea/js/combobox_1.js" ,
reader : {
type : "json"
}
},
autoLoad : true
});
var upform = Ext.create( 'Ext.form.Panel' , {
renderTo : 'adminfileupdata' ,
width : 500 ,
id : "upform" ,
frame : true ,
title : '文件上传' ,
bodyPadding : '10 10 0' ,
x : 40 ,
y : 40 ,
defaults : {
anchor : '100%' ,
allowBlank : false ,
msgTarget : 'side' ,
labelWidth : 100
},
items : [{
xtype : 'combobox' ,
fieldLabel : '文件用途' ,
emptyText : '请选择文件用途分类' ,
store : store,
displayField : 'text' ,
valueField : 'flag' ,
name : 'flag'
}, {
xtype : 'textfield' ,
fieldLabel : '自定义文件名称' ,
emptyText : '请自定义文件名称,必填!' ,
name : "uplname"
}, {
xtype : 'filefield' ,
id : 'form-file' ,
emptyText : '请选择本地文件' ,
fieldLabel : '上传地址' ,
name : 'upl' ,
buttonText : '上传' ,
buttonConfig : {
iconCls : 'upload-icon'
}
}],
buttons : [{
text : '上传' ,
handler : function() {
var form = this .up( 'form' ).getForm();
if (form.isValid()) {
form.submit({
url : 'uploadAdmin.do' ,
waitMsg : '正在上传您的文件,请耐心等候...' ,
success : function(form, action) {
Ext.Msg.alert( '提示信息' , "文件保存成功" );
},
failure : function() {
Ext.Msg.alert( "提示信息" , "对不起,文件保存失败" );
}
});
}
}
}, {
text : '重置' ,
handler : function() {
this .up( 'form' ).getForm().reset();
}
}]
});
});


?
[{
'text' : '可执行sql文件(TXT)' ,
'flag' : '1'
}, {
'text' : '普通文件' ,
'flag' : '2'
}]


?
/**
* 资源文件上传到服务器
*/
public void uploadAdmin() {
String flag = this .servletRequest.getParameter( "flag" );
String uplname = this .servletRequest.getParameter( "uplname" );
String filePath = this .getDocumentAdminPath() + uplFileName;
File file = new File(filePath);
/**
* 保存文件
*/
ResourceFile a = new ResourceFile();
a.setCreateDate( new Date());
a.setContentType( this .uplContentType);
a.setFilePath( "/document/admin/" + uplFileName);
a.setFlag(Integer.parseInt(flag));
a.setExeNumber( 0 );
a.setExtension(ActionUtil.getExtention(uplFileName).substring( 1 ));
a.setName(uplname);
/**
* 复制文件到磁盘
*/
ActionUtil.copy(upl, file);
try {
this .hibernateService.save(a);
} catch (Exception e) {
e.printStackTrace();
}
/**
* 返回结果
*/
// JSONObject json = new JSONObject();
// json.put("msg", "文件上传成功");
// json.put("success", "true");
// System.out.println(json.toString());
// JsonResult.json(json.toString(), servletResponse);
}


复制代码
    <action name="uploadAdmin" class="fileAction"            method="uploadAdmin">
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">                    application/vnd.ms-word, application/vnd.ms-excel,                    application/pdf, text/plain,application/kswps                </param>
                <param name="maximumSize">104857600</param>
                <param name="savePath">/upload</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack" />
            <result name="success">${successValue}</result>
            <result name="r" type="redirect">${successValue}</result>
        </action>

*******************************************************************************

Ext 文件上传

b7fd5266d01609247e6d9ec0d40735fae7cd34a46a63f6246b600c33c795e2131a4c510fd8f9a178上传完了之后地址会加载到上传内容这个文本框里面 962bd40735fae6cda13c97ba0fb30f2443a70f64 里面还做了类型判断,用于上传文本和相片代码如下,把一下代码封装在一个js文件里面


//*****************************************上传的公共js***************************************************************//


/**


* 约定:types为调用时传来的参数.形式为jsp-gig-png


*      uploadid为上传后要填充路径的控件id


*      上传的属性均为upload


* 功能:页面调用openUpload("","");方法即可


*/


//...允许上传的后缀名


var types = "";




//...上传后填充控件的id


var uploadid = "";




function openUpload(type,id){


 types = type;


uploadid = id;


 winUpload.show();


 }




var formUpload = new Ext.form.FormPanel({


   baseCls: 'x-plain',


   labelWidth: 80,


   fileUpload:true,


   defaultType: 'textfield',


   items: [{


     xtype: 'textfield',


     fieldLabel: '文 件',


     name: 'upload',


     inputType: 'file',


     allowBlank: false,


     blankText: '请上传文件',


     anchor: '90%'  // anchor width by percentage


   }]


 });




var winUpload = new Ext.Window({


   title: '资源上传',


   width: 400,


   height:200,


   minWidth: 300,


   minHeight: 100,


   layout: 'fit',


   plain:true,


   bodyStyle:'padding:5px;',


   buttonAlign:'center',


   items: formUpload,


   buttons: [{


     text: '上 传',


     handler: function() {


       if(formUpload.form.isValid()){


         Ext.MessageBox.show({


              title: 'Please wait',


              msg: 'Uploading...',


              progressText: '',


              width:300,


              progress:true,


              closable:false,


              animEl: 'loding'


            });


         formUpload.getForm().submit({    


  url:'uploadAction.action?types='+types,


           success: function(form, action){


 var objxzdz = Ext.get(uploadid).dom;


 var value = action.result.msg;


 objxzdz.value = value;


              Ext.Msg.alert('成功','上传成功.');


              winUpload.hide();  


           },    


            failure: function(form, action){    


//... action生成的json{msg:上传失败},页面就可以用action.result.msg得到非常之灵活


             Ext.Msg.alert('Error', action.result.msg);    


            }


         })          


       }


      }


   },{


     text: '取 消',


     handler:function(){winUpload.hide();}


   }]


 });


//*****************************************上传的公共js***************************************************************//


现在已经封装完毕了,我们看看在页面上如何调用

openUpload("txt-xls-doc-docs-pds","xzdzid");

就这一句话,嘿嘿,简单吧?第一个参数为允许上传的类型,第二个参数为上传后地址要绑定到哪个控件(是该控件的id)


action的代码还是贴下吧

<pre class="java" name="code">import java.io.File;


import java.io.FileInputStream;


import java.io.FileOutputStream;




import org.apache.struts2.ServletActionContext;




import net.ask123.ecommerce.common.util.Common;


import net.ask123.ecommerce.common.util.Constants;


import net.ask123.ecommerce.common.util.FileOperate;


import net.ask123.ecommerce.common.util.VeDate;




/**


* 上传的公共方法


*


* @author sam.zhang


*


*/


public class UploadAction extends ExtJsonActionSuport {




/**


*


*/


private static final long serialVersionUID = 1L;



       //和前台的名字一样,这里约定是 upload

&nbsp;       private File upload;




private String uploadContentType;




private String uploadFileName;




private String savePath;




// 存放允许上传的后缀名


private String types;




public String getSavePath() {


return savePath;


}




public void setSavePath(String savePath) {


this.savePath = savePath;


}




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;


}




public String getTypes() {


return types;


}




public void setTypes(String types) {


this.types = types;


}




@SuppressWarnings("deprecation")


public String execute() throws Exception {


String msg = "";


FileOperate fo = new FileOperate();




String sid = VeDate.getNo(4);




this.savePath = "/updownFiles";




try {




// ...获取文件后缀名


String ext = fo.getFileExt(getUploadFileName());




if ("".equals(this.types)


|| Common.indexofString(this.types, "-") == -1) {


msg = "上传失败";


this.setJsonString("{success:false,msg:'" + msg + "'}");


return SUCCESS;


}




// ...判断上传的文件是否合法


boolean istrue = FileOperate.trueExt(this.types.split("-"), ext);


if (!istrue) {


msg = "您上传的文件格式不正确,正确格式为" + this.types;


this.setJsonString("{success:false,msg:'" + msg + "'}");


return SUCCESS;


}




// ...文件存放的位置


String sPath = ServletActionContext.getRequest().getRealPath(


this.getSavePath())


+ Constants.FILESPARA


+ sid.substring(0, 4)


+ Constants.FILESPARA


+ sid.substring(4, 6)


+ Constants.FILESPARA;




// ...保存在数据库的路径


String filePath = this.savePath + "/" + sid.substring(0, 4) + "/"


+ sid.substring(4, 6) + "/" + sid + "." + ext;




// 如果目录不存在则创建它




fo.createFolder(sPath);




FileOutputStream fileOutputStream = new FileOutputStream(sPath


+ sid + "." + ext);




FileInputStream fileInputStream = new FileInputStream(getUpload());


// ...


byte[] buffer = new byte[1024];


int len = 0;


while ((len = fileInputStream.read(buffer)) > 0) {


fileOutputStream.write(buffer, 0, len);


}


this.setJsonString("{success:true,msg:'" + filePath + "'}");


} catch (Exception e) {


this.setJsonString("{success:false}");


e.printStackTrace();


}


return SUCCESS;


}