jsp中使用jquery的ajaxSubmit方法实现现异步上传

 

 

html代码:

<FORM name="frmPostSC" id="frmPostSC" method="Post" action="<%=request.getContextPath()%>/Ga-Sy/ZaJcxxDaxxDjAction.do?method=ExeclReader" enctype="multipart/form-data" >           
       <fieldset style = "width: 98%;text-align:center;"><legend>导入</legend> 
         <DIV id=infor style="FONT-SIZE: 11px; WIDTH: 100%; COLOR: red; FONT-FAMILY: arial; POSITION: relative; HEIGHT: 14px; TEXT-ALIGN: center"></DIV>      
       	 <INPUT type="file" name="cmdExecl" style="width:300px;" id="cmdExecl" class='Edit'">    
         <INPUT type="button" name="cmdExeclReader" id="cmdExeclReader" class="Button" value="开始导入" onclick="doExeclReaderSC();">
       </fieldset> 
       </FORM>

 

JS代码:

<script type="text/javascript" src="<%=request.getContextPath()%>/js/JQuery/jquery-1.4.4.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/JQuery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/JQuery/jquery.form.js"></script>
function doExeclReaderSC(){
    unBtns(["cmdExeclReader"]);
	$("#frmPostSC").ajaxSubmit({
        target:"#infor",
		type: "post",
		dataType: "script",  
		beforeSubmit: function(formData, jqForm, options){
				document.getElementById("infor").innerText='正在装载数据,请耐心等待...';
				return true;
		},
		success:function (msg) { 
		        var arr=msg.split(",");
				document.getElementById("infor").innerText=arr[0];
				doExeclReader(arr[1]);							      
	   }
	});
	//inBtns(["cmdExeclReader"]);
}
function doExeclReader(val)
{
    // 把字符串中的所有 \ 替换成 / 
    val = val.replace(/\\/g,"/") ;

	if (window.XMLHttpRequest)
	{
	  xmlhttp=new XMLHttpRequest();
	}
	else
	{
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	//unBtns(["cmdExeclReader"]);
	var url = strAction+"?method=doReader&URL="+encodeURI(encodeURI(val));
	xmlhttp.onreadystatechange=CallBackFunction;
	xmlhttp.open("GET",url,true);
	xmlhttp.send();
}
function CallBackFunction()
{
   if(xmlhttp.readyState==1){
   		document.getElementById("infor").innerText="由于数据量较大,可能会一段时间,请耐心等待,千万不要操作页面,正在导入中,请稍候...";	
   }
   else if(xmlhttp.readyState==3){
   		document.getElementById("infor").innerText="由于数据量较大,可能会一段时间,请耐心等待,千万不要操作页面,正在导入中,请稍候...";	
   }else if(xmlhttp.readyState==0){
   		document.getElementById("infor").innerText=xmlhttp.responseText;
   }
   else if (xmlhttp.readyState==4 && xmlhttp.status==200)
   {
    	document.getElementById("infor").innerText=xmlhttp.responseText;
    	inBtns(["cmdExeclReader"]);   
   }
}

 

 

Action代码:

import java.io.File;
import java.sql.Connection;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.dom4j.Document;
import org.dom4j.Element;

public class ZaJcxxDaxxDjAction
    extends BaseDispatchAction {
public ActionForward ExeclReader(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {    
    	System.out.println("进入ExeclReader方法");
    	 User user = (User)request.getSession().getAttribute(com.framework.Globals.USER_KEY);
    	 //RightManager.checkPower(request, response, "");
    	 Connection conn = DBUtil.getConnection(); 
    	 try {
    		   DiskFileItemFactory dfif = new DiskFileItemFactory();
    		   ServletFileUpload upload = new ServletFileUpload(dfif);
    		   upload.setSizeMax(10 * 1024 * 1024); // 允许上传的最大值
    		   request.setCharacterEncoding("GBK");
    		   List list = upload.parseRequest(request); // 开始解析request对象中的表单数据
    		   if (list.size() >= 1) {
	    		    FileItem item = (FileItem) list.get(0);
	    		    String name = item.getName();
	    		    name = name.substring(name.lastIndexOf("\\") + 1);
	                String path = "tempFile";
	                ServletContext ctx = this.getServlet().getServletContext();
	    		    path = ctx.getRealPath(path);
	    		    File file = new File(path);
	    		    if(!file.exists()){
	    		     System.out.println("创建文件夹");
	    		     file.mkdir();
	    		    }	
	    		    System.out.println(path);
	    		    System.out.println(name);
	    		    //将文件放到指定的地方
	    		    item.write(new File(path, name));
	    		    System.out.println("数据装载完成...") ;
	    		    Pub.writeMessage(response,"数据装载完成...!,"+path+"\\"+name);
    		   }
    		  } catch (Exception e) {
    		   throw new Exception("file upload error!", e);
    		  }
    	 
    return null;
    }
    public ActionForward doReader(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	 System.out.println("进入doReader方法");
    	 User user = (User)request.getSession().getAttribute(com.framework.Globals.USER_KEY);
    	 String url=java.net.URLDecoder.decode(request.getParameter("URL"), "UTF-8");
    	 Connection conn = DBUtil.getConnection();
    	 Statement stmt = conn.createStatement();        
	     Workbook workbook = null;
	     Sheet sheet =null;
	     Cell cell = null;
	     try {
	    	System.out.println(url);
	        workbook = Workbook.getWorkbook(new File(url));
		    sheet= workbook.getSheet(0);
		    int columnCount=sheet.getColumns();
		    int rowCount=sheet.getRows();
		    System.out.println("开始导入...");
		    for (int i = 2; i <rowCount; i++) {
		    	if("".equals(sheet.getCell(1, i).getContents())){
		    		break;
		    	}
		    	String sql="insert into ZA_JCXX_DAXX_DJ (xh,AJH,DABT,DQBTPY,DAXZ,DAND,BGQX,GLDWDM,DALB,QZH,TBR,TBSJ,CXBS) values('"+com.common.SequenceUtil.getCommonSerivalNumber()+"'";		     
		        for (int j = 1; j <9; j++) {//注意,这里的两个参数,第一个是表示列的,第二才表示行
		            cell=sheet.getCell(j, i); //要根据单元格的类型分别做处理,否则格式化过的内容可能会不正确			            
            		sql=sql+",'"+cell.getContents()+"'";
            		if(j==2){
            			sql=sql+",'"+SpellCache.getInstance().getAspell(cell.getContents())+"'";
            		}		
		            
		        }
		        
		        Date date=new Date();
		        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
		        String sj=df.format(date);
		        sql+=",'"+user.getAccount()+"',to_date('"+sj+"','yyyy-MM-dd'),'0')";
		        System.out.println(sql);
		        stmt.execute(sql);	                    
		        sql="";
		    }
		  System.out.println("完成导入...");
		  workbook.close();
		  stmt.close();
          stmt = null;	
		  conn.commit();
		  Pub.writeMessage(response,"导入成功!");
		  }catch (Exception e) {
			  Pub.writeMessage(response,"导入失败!");
	          conn.rollback();
	          stmt.close();
	          stmt = null;	
	          workbook.close();
	          e.printStackTrace(System.out);	        	  	    
		 }   
    return null;
    }
}

 

 

 

 

 

 

 

你可能感兴趣的:(jquery,jsp,ajaxSubmit)