jquery+ajax+struts实现文件上传

 
 

首先在前段引入jquery.js和ajaxfileupload.js文件,一般引入放在最后面,这样可以通过jquery的jQuery.noConflict();方法避免冲突,其中jquery.js和ajaxfileupload.js建议放于引入的js中的最后面,比较容易解决冲突。引入js

<script type="text/javascript" language="javascript" src="/js/jquery-1.6.3.min.js"></script>
<script type="text/javascript" language="javascript" src="/js/ajaxfileupload.js"></script>

ajaxfileupload.js

json及其依赖的jar

html:

<input type="button" value="导入" onclick="return ajaxFileUpload();" style="width: 50px; height: 18px;">

js上传方法:

 jQuery.noConflict(); //解决jquery冲突问题
    function ajaxFileUpload()
    {
   
      var fileVal = jQuery("#file").attr("value");
  
        var fileValArr = fileVal.split(".");
        if(fileValArr[fileValArr.length-1] != 'xls') {
        	alert("请上传excel文件!");
        	return false;
        }
        jQuery("#loading")
        .ajaxStart(function(){
           jQuery(this).show();
        })//开始上传文件时显示一个图片
        .ajaxComplete(function(){
           jQuery(this).hide();
        });//文件上传完成将图片隐藏起来
        jQuery.ajaxFileUpload
        (
            {
                url:'cjlrNewExcelAction.do',//用于文件上传的服务器端请求地址
                secureuri:false,//一般设置为false 这个为空ajaxfileupload中的iframe不显示
                fileElementId:'file',//文件上传空间的id属性  <input type="file" id="file" name="file" />
                dataType: 'json',//返回值类型 一般设置为json
                success: function (data, status)  //服务器成功响应处理函数
                {
                	//这里放入返回成功后需要处理的响应data是返回的数据
                	alert(data);
                	//逻辑处理  下面是我的逻辑处理
                		for(var i = 0; i< data.length; i++){
                		var dataVal = data[i].split("--");
                    	var xh = dataVal[1];
                    	var pscj = dataVal[4];
                    	
                    	if (pscj == 'nothing') {
                    		pscj = '';
                    	}
                    	
                    	var qmcj = dataVal[5];
                    	if (qmcj == 'nothing') {
                    		qmcj = '';
                    	}
                    	
                    	var wtgyy = dataVal[6];
                    	if (wtgyy == 'nothing') {
                    		wtgyy = '';
                    	}
                    	
                    	}
                    
                },
                error: function (data, status, e)//服务器响应失败处理函数
                {
                   //服务器响应失败的处理信息。
                }
            }
        )
        return false;
    }

以上是js的为客户端上传,其中调用了ajaxfileupload.js中的方法。ajaxfileupload采用 jquery.extend({}),的方式在jquery中添加对象。

其中Action中负责接收数据和解析。

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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

import net.sf.json.JSONArray;

import org.apache.poi2.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;


public class NewExcelAction extends BaseAction {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String oper = request.getParameter("oper");
		HttpSession  session = request.getSession(true);
		if (oper == null || "".equals(oper)) {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Expires", "0");
			response.setContentType("text/html;charset=UTF-8");
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
			// response.setCharacterEncoding("UTF-8");

			NewExcelForm excelForm = (NewExcelForm) form;

			if (excelForm.getMultipartRequestHandler().getFileElements().get(
					"file") == null) {
			} else {

				FormFile file = (FormFile) excelForm
						.getMultipartRequestHandler().getFileElements().get(
								"file");
				String fileName = file.getFileName();
				String fileSimpleName = fileName.substring(fileName
						.lastIndexOf("."));
				System.out.println(fileName);
				List<String> list = new ArrayList<String>();
				try {
					list = new UpLoadExcel()
							.getExcelData(file.getInputStream());
					JSONArray js = new JSONArray();
					JSONArray jr = js.fromObject(list);
					System.out.println(jr);
					PrintWriter out = response.getWriter();
					out.print(jr);
					out.flush();
					out.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		} else if ("excel".equals(oper)) {
			
			
			ArrayList xsmdArrayList = (ArrayList)session.getAttribute("showInfor");
			ShowXsmdVo showXsmdVo = new ShowXsmdVo();
			
			
			BufferedOutputStream output;
			try {
				output = new BufferedOutputStream(response.getOutputStream());
				response.setHeader("Content-disposition",
						"attachment;filename="
								+ new String("录入模板".getBytes("gbk"),
										"iso8859-1") + ".xls");
				HSSFWorkbook workbook = cjlrBo.createExecl(xsmdArrayList);
				workbook.write(output);
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

上传的excel文件,其中public class NewExcelForm extends ActionForm {

}必须有,是为了使用ActionForm中的.getMultipartRequestHandler().getFileElements().get("file")方法, file.getInputStream()用于通过流的方式得到数据,

list = new UpLoadExcel()
.getExcelData(file.getInputStream()); 用于对得到的数据进行解析,如果是其他类型的数据就进行其他类型的解析。

JSONArray js = new JSONArray();
JSONArray jr = js.fromObject(list); 把解析到的包装成json格式,方便传输。

PrintWriter out = response.getWriter();
out.print(jr);
out.flush();
out.close();  已流的方式写出到页面。

下面那个是下载模板方法,如果你上传的文件需要是固定格式,可以以模板下载的方式下载模板。

对应的struts的配置:

     <form-bean name="NewExcelForm" type="包名.NewExcelForm" />


 <action path="/NewExcelAction"  name="NewExcelForm"  scope="request" type="包名.NewExcelAction" validate="true">
   
    </action> 

ajaxfileupload.js文件如下:

jQuery.extend({
	

    createUploadIframe: function(id, uri)
	{
		//create frame
		var frameId = 'jUploadFrame' + id;
		if(window.ActiveXObject) {
			if(jQuery.browser.version=="9.0"){
				var io = document.createElement('iframe');
				io.id = frameId;
				io.name = frameId;
			}else if(jQuery.browser.version=="6.0" || jQuery.browser.version=="7.0" || jQuery.browser.version=="8.0"){
				 var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
				 if(typeof uri== 'boolean'){
					 io.src = 'javascript:false';
				 }
				 else if(typeof uri== 'string'){
					 io.src = uri;
				 }
			}
		}
		else {
			var io = document.createElement('iframe');
			io.id = frameId;
			io.name = frameId;
		}
		io.style.position = 'absolute';
		io.style.top = '-1000px';
		io.style.left = '-1000px';

		document.body.appendChild(io);

		return io;	
    },
    createUploadForm: function(id, fileElementId)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },
	addOtherRequestsToForm: function(form,data)
	{
		// add extra parameter
		var originalElement = jQuery('<input type="hidden" name="" value="">');
		for (var key in data) {
			name = key;
			value = data[key];
			var cloneElement = originalElement.clone();
			cloneElement.attr({'name':name,'value':value});
			jQuery(cloneElement).appendTo(form);
		}
		return form;
	},

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()        
		var form = jQuery.createUploadForm(id, s.fileElementId);
		if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{
           // var io = jQuery('#' + frameId);
			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';				
            }
            else
			{				
                form.enctype = 'multipart/form-data';
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        } 		
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
            eval( "data = " + data );
        // evaluate scripts within html
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();
			//alert(jQuery('param', data).each(function(){alert(jQuery(this).attr('value'));}));
        return data;
    }
})





你可能感兴趣的:(jquery+ajax+struts实现文件上传)