Jquery + Ajax + Struts implement File Upload

Source: Internet
Author: User
 
First, introduce jquery. JS and ajaxfileupload. JS files are generally introduced at the end, so you can use jquery's jquery. noconflict (); method to avoid conflicts, among which jquery. JS and ajaxfileupload. JS is recommended to be placed at the end of the introduced js to easily resolve conflicts. 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 its dependent jar

HTML:

<Input type = "button" value = "import" onclick = "Return ajaxfileupload ();" style = "width: 50px; Height: 18px;">

JS upload method:

Jquery. noconflict (); // solves jquery conflicts. Function ajaxfileupload () {var fileval = jquery ("# file "). ATTR ("value"); var filevalarr = fileval. split (". "); If (filevalarr [filevalarr. length-1]! = 'Xls ') {alert ("please upload an Excel file! "); Return false;} jquery (" # loading "). ajaxstart (function () {jquery (this ). show () ;}) // an image is displayed when the file is uploaded. ajaxcomplete (function () {jquery (this ). hide () ;}); // hide the image after the file is uploaded. jquery. ajaxfileupload ({URL: 'cjlrnewexcelaction. do ', // secureuri of the server request address used for file upload: false, // It is generally set to false. If this parameter is left blank, IFRAME in ajaxfileupload does not display fileelementid: 'file ', // ID attribute of the file upload space <input type = "file" id = "file" name = "file"/> datatype: 'json', // Return Value Type Generally set to JSON success: function (data, status) // server success Response Processing Function {// here, the response data to be processed after the return is successful is the returned data alert (data ); // below is my logic 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 (data, status, e) // server response failed processing function {// server response failed processing information. }) Return false ;}

The above is the upload of Js for the client, where the method in ajaxfileupload. JS is called. Ajaxfileupload uses jquery. Extend ({}) to add objects to jquery.

The action is responsible for receiving and parsing data.

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 response = request. getparameter ("parameter"); httpsession session = request. getsession (true); If (response = NULL | "". equals (response) {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 (events) {arraylist xsmdarraylist = (arraylist) session. getattribute ("showinfor"); 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 ;}}

The uploaded Excel file, where public class newexcelform extends actionform {

} It must exist to use the. getmultipartrequesthandler (). getfileelements (). Get ("file") method in actionform. file. getinputstream () is used to obtain data through a stream,

List = new uploadexcel ()
. Getexceldata (file. getinputstream (); it is used to parse the obtained data. If it is other data types, it is parsed by other types.

Jsonarray JS = new jsonarray ();
Jsonarray Jr = Js. fromobject (list); packs parsed data into JSON format for easy transmission.

Printwriter out = response. getwriter ();
Out. Print (JR );
Out. Flush ();
Out. Close (); writes the stream to the page.

The following is the template download method. If the file you upload needs to be in a fixed format, you can download the template as a template.

Corresponding struts Configuration:

<Form-bean name = "newexcelform" type = "package name. newexcelform"/>

<Action Path = "/newexcelaction" name = "newexcelform" Scope = "request" type = "package name. newexcelaction" Validate = "true">

</Action>

The ajaxfileupload. js file is as follows:

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;    }})

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.