Using Ajaxfileupload.js to implement AJAX upload files PHP version _jquery

Source: Internet
Author: User
Tags new set php script jquery library

Whether PHP, or other server-side scripts provide the file upload function, the implementation is relatively simple. and using JavaScript to match, you can achieve AJAX-style file upload. Although jquery itself does not provide such a simplified function, there are a number of plug-ins that can be implemented. Among them, the ajaxfileupload.js provided by Phpletter.com is a lightweight plug-in and is written in a way that is very similar to the global approach provided by jquery $.post () and is easy to use.
However, the plugin is simply too simplistic to deliver additional values to the backend server, in addition to the path to upload files. So, I modified the script to add a data object parameter.

First, the principle

I'm using PHP as a server-side script, and almost every book with less PHP mentions how to use the Move_uploaded_file () method to upload files, and I'm not going to elaborate on them here. What I want to say is, use Ajax to upload the principle.
Because you've been using the jquery library, when you think of Ajax, the first reaction is to try the $.post () method, use each selector to get the value in the File box, and then submit it to the backend server. Of course, it turns out that's not going to work. (Because of this problem, I also checked a lot of information, online also provides a lot of ASP and other ways of scripting, I really do not know what to say good. )
Back to the point, to achieve Ajax way to upload, in fact, not difficult, there are many methods. The phpletter.com ajaxfileupload.js Plug-ins mentioned in this article are the way to use IFRAME. This is also a common way to implement not refreshing page uploads when you are not using JavaScript scripts. (This blog Bo-blog background writing log is to use this method)
And the Ajaxfileupload.js plug-in is also very simple, is the first use of jquery selector to get file File upload box path value, and then dynamically create an IFRAME, and inside the creation of a new file box, provide post method submitted to the background. Finally, return the results to the foreground.

Second, the use

The use of Ajaxfileupload.js plug-ins is simple.
The foreground HTML code is similar:

<script type= "Text/javascript" >
$ (#buttonUplod). Click (function () {
 $.ajaxfileupload ({
  URL: ' Doajaxfileupload.php ',//You handle the secureuri:false of the uploaded file,//the
  ID value corresponding to file in the page processing code
  fileelementid: ' img ',
  DataType: ' json ',//Return data type: TEXT,XML,JSON,HTML,SCRITP,JSONP five kinds of
  success:function (information) {
   alert (data.file_ infor);}})
;
</script>
<input id= "img" type= "file" size= "" "Name=" img ">

Background doajaxfileupload.php script:

<?php
 $upFilePath = ". /attachment/";
$ok = @move_uploaded_file ($_files[' img '] [' tmp_name '], $upFilePath);
 if ($ok = = FALSE) {
  echo json_encode (' file_infor ' => ' upload failed ');
 } else{
  Echo json_encode (' file_infor ' => ' upload succeeded ');
> 


For testing purposes, you can save the value of a variable passed over by using a method similar to the following:

$file _info = Var_export ($_files,true);
$ok = File_put_contents (". /attachment/file_info.txt ", $file _info);
if ($ok) exit (Json_encode (' file_infor ' => ' uploaded success '));
Exit (Json_encode (' file_infor ' => ' upload failed '));


※ Note
Note the markup in the HTML code file box:

1. Id= ' img ' is used to give the Ajaxfileupload.js plug-in fileelementid: ' img ' identified, the jquery selector will use the string to obtain the value of the text box;
2. Name= ' img ' is used to submit the post to the background script, PHP through the $_files[' img '] read the uploaded file data, if not the value, the $_files variable is empty;

Therefore, these two values are indispensable and can not be confused.

Third, support additional parameters

Sometimes, we need to be in the background according to some variables to feel the processing of uploaded files. For example, update the file. At this point, you need to pass some additional parameters to the same station. So, I modified the Ajaxfileupload.js plugin:

Addotherrequeststoform:function (Form,data)
{
 //Add extra parameter
 var originalelement = $ (' <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});
  $ (cloneelement). appendto (form);
 return form;
}, 

ajaxfileupload:function (s) {
 //TODO introduce global settings, allowing the client to MoD Ify 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); 

The Red Flag section is what I added. In this way, I can pass additional parameters in the foreground HTML section by using code similar to the following:

URL: ' doajaxfileupload.php ',//You process the service side of the uploaded file
Secureuri:false,//ID value corresponding to file in page processing code
data:{' test ': ' Test ', ' OK ': ' OK '},//passed as Object, Content section can enter JavaScript variable value
Fileelementid: ' img ',

The background processing script is:

Array_push ($_files,$_request);
$file _info = Var_export ($_files,true);
$ok = File_put_contents (". /attachment/file_info.txt ", $file _info);
if ($ok) exit (Json_encode (' file_infor ' => ' uploaded success '));
Exit (Json_encode (' file_infor ' => ' upload failed ')); 

Visible, the principle is very simple, that is, the additional data object content added to the iframe under the form, passed to the background php script, to $_request and other variables to obtain these values.
The file_info.txt contents of the background output are as follows:

Array (
' File ' =>
Array (
' Name ' => ' Firefox-java.txt ',
' Type ' => ' Text/plain ',
' Tmp_name ' => ' d:\\tools\\xampp\\tmp\\phped45.tmp ',
' Error ' => 0,
' Size ' => 250,
),
0 =>
Array (
' Test ' => ' test ',
' OK ' => ' OK ',
' Phpsessid ' => ' e379fd4fb2abca6e802a1302805a5535 ',
),
)

Ajaxfileupload.js:

Jquery.extend ({createuploadiframe:function (id, URI) {//create frame var Frameid = ' juploadframe ' + id; if window.
ActiveXObject) {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 = $ (' <form action= "" method= "POST" name= "' + Formid + '" id= "' + Formid + '" enctype= "Multipart/form-data" > 
 </form> ');
 var oldelement = $ (' # ' + Fileelementid);
 var newelement = $ (oldelement). Clone ();
 $ (oldelement). attr (' id ', fileid);
 $ (oldelement). before (newelement);$ (oldelement). appendto (form);
 Set attributes $ (form). CSS (' position ', ' absolute ');
 $ (form). CSS (' top ', ' -1200px ');
 $ (form). CSS (' left ', ' -1200px '); 
 $ (form). Appendto (' body ');
  return form; }, Addotherrequeststoform:function (form,data) {//Add extra parameter var originalelement = $ (' <input type= ' Hidde
 N "name=" "value=" ">");
  for (var key in data) {name = key;
  Value = Data[key];
  var cloneelement = Originalelement.clone ();
  Cloneelement.attr ({' name ': Name, ' Value ': value});
 $ (cloneelement). appendto (form);
 } return form; }, Ajaxfileupload:function (s) {//TODO introduce global settings, allowing the client to modify them for all req
    Uests, 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 (f
Rameid); try {if (Io.contentwindow) {xml.responsetext = Io.contentwindow.document.body?io.contentwindow.document.body.i
 Nnerhtml: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 XM  
L 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 {$ (IO). Remove (); 
     $ (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 happening if (!requestdone) uploadcallback ("timeout");
    }, S.timeout);
  try {//var IO = $ (' # ' + Frameid);
  var form = $ (' # ' + formid);
  $ (form). attr (' action ', S.url);
  $ (form). attr (' method ', ' POST ');
$ (form). attr (' target ', Frameid);  
if (form.encoding) {form.encoding = ' multipart/form-data ';  
else {form.enctype = ' multipart/form-data ';} 

    $ (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 ($ (' param ', data). each (function () {Alert ($ (this). attr (' value '));
  return data;  }
})

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.