Use ajaxfileupload. js to upload files to php through ajax

Source: Internet
Author: User
Tags php book

Both PHP and other server scripts provide the file upload function, which is easy to implement. With JavaScript, you can upload files in Ajax mode. Although jQuery does not provide such a simplified function, many plug-ins can implement it. Among them, the ajaxfileupload. js provided by Phpletter.com is a lightweight plug-in, and the writing method is very similar to the Global Method $. post () provided by jQuery, which is easy to use.
However, this plug-in is too simplified. In addition to providing the path for uploading files, you cannot transmit additional values to the backend server. So I modified the script and added a data object parameter.

I. Principles

I am using PHP as a server script. I will mention how to use the move_uploaded_file () method to upload files in almost every small PHP book. I will not elaborate on it here. I want to talk about the principle of using Ajax for upload.
Because the jQuery library is used all the time, 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 this is not feasible. (Because of this problem, I also checked a lot of information and provided a lot of ASP scripts on the Internet. I really don't know what to say ..)
Back to the topic, it is not difficult to implement Ajax upload. There are also many methods. The Phpletter.com ajaxfileupload. js plug-in mentioned in this article uses iframe. This is also a common method for uploading without refreshing new pages when JavaScript scripts are not used. (This method is used to write logs in the bo-blog background)
While ajaxfileupload. the js plug-in is also very simple, that is, first use the jQuery selector to obtain the file path value in the file upload box, then dynamically create an iframe, and create a new file box in it, the post method is provided for submission to the background. Finally, return the result to the foreground.

Ii. Use

The use of the ajaxfileupload. js plug-in is simple.
The front-end HTML code is similar:

<Script type = "text/javascript" >$ (# buttonuplevels ). click (function () {$. ajaxFileUpload ({url: 'doajaxfileupload. php ', // secureuri: false on the server where you process the uploaded file, // The ID value fileElementId: 'img' corresponding to the file in the page processing code, dataType: 'json ', // return data type: Five success: function (data) {alert (data. file_infor );}})}); </script> <input id = "img" type = "file" size = "45" name = "img"> <button id = "buttonUpload" onclick = "return ajaxFileUpload (); "> Upload </button>

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 successful ');}?>


For testing, you can save the passed variable values in a way 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 '=> 'upload successful '));
Exit (json_encode ('file _ infor '=> 'upload failed '));


※Note
Pay attention to the markup in the HTML code file box:

1. id = 'img 'is used to identify the fileElementId: 'img' of the ajaxfileupload. js plug-in. The jQuery selector uses this string to obtain the value of the text box;
2. name = 'img 'is used to read the data of the uploaded file through $ _ FILES ['img'] When the file is submitted to the background through post. If this value is not set, the $ _ FILES variable is empty;

Therefore, these two values are indispensable and cannot be confused.

3. Support for additional parameters

Sometimes, we need to process the uploaded files in the background based on certain variables. For example, update a file. In this case, you need to pass some additional parameters to the same platform. Therefore, I modified the ajaxfileupload. js plug-in:

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

The red part is the content I added. In this way, I can pass additional parameters in the HTML section of the foreground using code similar to the following:

Url: 'doajaxfileupload. php', // the server on which you process the uploaded files
Secureuri: false, // ID value corresponding to the file in the page processing code
Data: {'test': 'test', 'OK': 'OK'}, // It is transmitted as an object. You can enter the JavaScript variable value in the content section.
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 successfully ')); exit (json_encode ('file _ infor '=> 'upload failed '));

It can be seen that the principle is very simple. It is to add the additional data object content to the form under iframe together, pass it to the PHP script in the background, and get these values with variables such as $ _ REQUEST.
The content of the remaining file_info.txt file in the background output is as follows:

Array (
'File' =>
Array (
'Name' => 'firefox-java.txt ',
'Type' => 'text/plain ',
'Tmp _ name' => 'd: \ Tools \ xampp \ tmp \ phpED45.tmp ',
'Error' => 0,
& Apos; size & apos; = & apos; 250 & apos,
),
0 =>
Array (
'Test' => 'test ',
'OK' => 'OK ',
'Phpsessid' => 'e0000fd4fb2abca6e802a1302805a5535 ',
),
)

Ajaxfileupload. js:

jQuery.extend({  createUploadIframe: function(id, uri) {  //create framevar 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="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 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 notmodifiedif ( 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 dataif ( s.success )s.success( data, status );// Fire the global callbackif( s.global )jQuery.event.trigger( "ajaxSuccess", [xml, s] );} elsejQuery.handleError(s, xml, status);} catch(e)  {status = "error";jQuery.handleError(s, xml, status, e);} // The request was completedif( s.global )jQuery.event.trigger( "ajaxComplete", [xml, s] ); // Handle the global AJAX counterif ( s.global && ! --jQuery.active )jQuery.event.trigger( "ajaxStop" ); // Process resultif ( s.complete )s.complete(xml, status); jQuery(io).unbind() setTimeout(function()     { try     {      $(io).remove();      $(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 happeningif( !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.