首先在前段引入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 framevar 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 formvar 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 attributesjQuery(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 parametervar 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; }})