Simple jquery ajax Upload plugin Ajaxfileupload

Source: Internet
Author: User
Tags eval extend new set

Doing Web applications often requires uploading.

So, Ajax uploads are often used.

Share a jquery Ajax upload component Ajaxfileupload.

The usage is simple:

The code is as follows Copy Code

<! DOCTYPE html>


<html lang= "en" >


<html>


<head>


<title> Upload demo</title>


<meta charset= "Utf-8" >


<script src= "/js/jquery-1.8.3.min.js" ></script>


<script src= "/js/ajaxfileupload.js" ></script>


</head>


<body>


<input type= "File" id= "FileInput" name= "good"/> <a href= "Javascript:upload ()" > Upload </a>


<script type= "Text/javascript" >


function upload () {


$.ajaxfileupload ({


ckeditor/"target=" _blank ">fckeditor/editor/'/upload.html '" >url: '/upload.html ',


Fileelementid: ' FileInput ',


Success:function (data, status)


{


Alert ("Success");


alert (data);


},


Error:function (data, status, E)


{


Alert ("Error");


Alert (e);


}


})


}


</script>


</body>


</html>

/upload.html is actually the general upload path.

Of course, sometimes when you use new jquery, you'll report handleerror anomalies.

It doesn't matter, it's the new jquery that's got rid of this method, we add one to the back of the component.

  code is as follows copy code

Handleerror:function (S, xhr, status, E) {
If a local callback is specified, fire it
if (s.error) {
S.error.call (S.context | | s, XHR, status, E);
}

Fire the global callback
if (S.global) {
(S.context jQuery (s.context): jquery.event). Trigger ("Ajaxerror", [XHR, S, E]);
}
}

It's as simple as that.

What is the modified component code?

The code is as follows Copy Code

Jquery.extend ({


Createuploadiframe:function (ID, URI)
{
Create frame
var Frameid = ' juploadframe ' + ID;
var iframehtml = ' <iframe id= ' + Frameid + ' "name=" ' + Frameid + ' "style=" position:absolute; top:-9999px; Left:-9999px "';
if (window. ActiveXObject)
{
if (typeof uri== ' Boolean ') {
iframehtml + = ' src= ' + ' javascript:false ' + ' ';

}
else if (typeof uri== ' string ') {
iframehtml + = ' src= ' + uri + ' ";

}
}
iframehtml + = '/> ';
JQuery (iframehtml). Appendto (Document.body);

return JQuery (' # ' + Frameid). Get (0);


},


Createuploadform:function (ID, fileelementid, data)


{


Create form


var formid = ' juploadform ' + ID;


var Fileid = ' juploadfile ' + ID;


var form = jQuery (' &lt;form action= "" method= "POST" name= "' + Formid + '" id= "' + Formid + '" enctype= "Multipart/form-dat A "&gt;&lt;/form&gt;");


if (data)


{


for (var i in data)


{


JQuery (' &lt;input type= "hidden" name= "' + i + '" value= "' + data[i] + '"/&gt; '). Appendto (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;
},

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, (typeof (S.data) = = ' undefined '? false: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 &amp;&amp;! 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


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 this 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 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 ("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-if the request is still happening
                 if (!requestdone) uploadcallback ("timeout");
           }, S.timeout);
       }
        try
        {

var form = jQuery (' # ' + formid);


JQuery (Form). attr (' action ', S.url);


JQuery (Form). attr (' method ', ' POST ');


JQuery (Form). attr (' target ', Frameid);


if (form.encoding)


{


JQuery (Form). attr (' Encoding ', ' multipart/form-data ');


}


Else


{


JQuery (Form). attr (' enctype ', ' multipart/form-data ');


}


JQuery (Form). Submit ();

catch (E)
{
Jquery.handleerror (s, XML, NULL, E);
}

JQuery (' # ' + Frameid). Load (uploadcallback);
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 ("&lt;div&gt;"). HTML (data). Evalscripts ();

return data;
},

Handleerror:function (S, xhr, status, E) {
If a local callback is specified, fire it
if (s.error) {
S.error.call (S.context | | s, XHR, status, E);
}

Fire the global callback
if (S.global) {
(S.context jQuery (s.context): jquery.event). Trigger ("Ajaxerror", [XHR, S, E]);
}
}
})

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.