First, introduce Jquery.js and ajaxfileupload.js files in the preceding paragraph, and generally introduce them to the last side, so that you can avoid conflicts by using JQuery's jquery.noconflict (); where Jquery.js and ajaxfileupload.js recommendations are placed in the last side of the introduced JS, it is easier to resolve the conflict. Introduce 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 and the jar it relies on
Html:
<input type= "button" value= "import" onclick= "return Ajaxfileupload ();" Style= "width:50px; height:18px; " >
JS Upload method:
Jquery.noconflict ();
Resolve the JQuery conflict problem function ajaxfileupload () {var fileval = jquery ("#file"). attr ("value");
var Filevalarr = Fileval.split ("."); if (filevalarr[filevalarr.length-1]!= ' xls ') {alert ("Please upload the Excel file.")
");
return false;
jquery ("#loading"). Ajaxstart (function () {jQuery (this). Show ();
)//Start uploading the file to display a picture. Ajaxcomplete (function () {jQuery (this). Hide (); //File Upload complete hides the picture jquery.ajaxfileupload ({url: ' cjlrnewexcelaction.do ',//For text The server-side request address secureuri:false,//is generally set to false this is an empty ajaxfileupload in the IFRAME does not show Fileelementid: ' fil
E ',//File upload Space id attribute <input type= "file" id= "file" name= "file"/> dataType: ' json ',//return value type is generally set to JSON Success:function (data, status)//server successful response processing function {//The response that you need to process to return success here is returned Data alert (dATA); Logical processing is my logical processing 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 (DA
TA, status, E)//server response failed processing function {//server response failed processing information.
}) return false; }
The above is JS for the client upload, which called the Ajaxfileupload.js in the method. Ajaxfileupload uses the Jquery.extend ({}) method to add objects to jquery.
Where the action is responsible for receiving data and parsing.
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 ("Showin
For ");
Showxsmdvo Showxsmdvo = new Showxsmdvo ();
Bufferedoutputstream output;
try {output = new Bufferedoutputstream (Response.getoutputstream ());
Response.setheader ("Content-disposition", "attachment;filename=" + new String ("Input template". GetBytes ("GBK"),
"Iso8859-1") + ". xls");
Hssfworkbook workbook = cjlrbo.createexecl (xsmdarraylist);
Workbook.write (output);
Output.close ();
catch (IOException e) {e.printstacktrace ();
} return null;
}
}
Upload the Excel file, where public class Newexcelform extends Actionform {
Must have, in order to use the. Getmultipartrequesthandler (). Getfileelements (). Actionform (), the. Get ("File") method, File.getinputstream () Used to get data through the flow,
List = new Uploadexcel ()
. Getexceldata (File.getinputstream ()); Used to parse the resulting data and to perform other types of parsing if it is other types of data.
Jsonarray js = new Jsonarray ();
Jsonarray Jr = Js.fromobject (list); The parsing to the packaging into a JSON format for easy transmission.
PrintWriter out = Response.getwriter ();
Out.print (JR);
Out.flush ();
Out.close (); The stream is written out to the page.
The following is the download template method, if you upload the file needs to be a fixed format, you can download the template template.
The configuration of the corresponding struts:
<form-bean name= "Newexcelform" type= package name. Newexcelform "/>
<action path= "/newexcelaction" name= newexcelform "scope=" Request "type=" package name. Newexcelaction "validate=" True >
</action>
Ajaxfileupload.js files are as follows:
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 = d
Ocument.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-dat
A "></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 ("Ajax
Start ");
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.getelemen
Tbyid (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.b
Ody.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 this request was successful or notmodified if (status!= "error") { // Process the data (runs the XML through Httpdata regardless of callback) var data = Jquery.uploadh
Ttpdata (XML, S.datatype);
If a local callback is 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 ("Ajax
Success ", [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); }}, XML = null}}//Timeout checker if ( S.timeout > 0) {settimeout (function () {//Check to = If the request is still Happeni
ng 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;
}
})