Using ajaxfileupload.js ajax upload file PHP version

  • 2020-03-30 03:25:45
  • OfStack

  Both PHP and other server-side scripts provide file upload functionality and are relatively simple to implement. And the use of JavaScript to cooperate, you can achieve Ajax way of file upload. While jQuery itself doesn't provide such a simplified function, there are a number of plug-ins available. Among them, the ajaxfileupload.js provided by Phpletter.com is a lightweight plug-in that is written in a way very similar to the global method $.post() provided by jQuery.
However, the plug-in is too simple to pass additional values to the backend server, except to provide a path to the file to be uploaded. So, I modified the script to add a data object parameter.

A, 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, so I won't go into details here. What I want to talk about is the principle of using Ajax to upload.
Because you've been using the jQuery library, when you think of Ajax, your first thought is to try the $.post() method, which USES each selector to get the value in the file box and then submits it to the backend server. Of course, this proved impossible. Because of this problem, I also looked up a lot of information, also provided a lot of ASP and other ways of the script, really don't know what to say.
Getting back to the point, it's not that hard to do an ajax-style upload, and there are many ways to do it. The ajaxfileupload.js plug-in for Phpletter.com mentioned in this article is the way to use an iframe. This is also a common way to implement a page upload without refreshing it without using JavaScript scripts. (this blog bo-blog background writing blog is using this method)
The ajaxfileupload.js plug-in is also very simple, which is to first use jQuery selector to get the file path value in the fileupload box, and then dynamically create an iframe, and set up a new file box in it, provide a post method to submit to the background. Finally, return the result to the foreground.

Second, the use of

The ajaxfileupload.js plug-in is simple to use.
The foreground HTML code is similar to:


<script type="text/javascript">
$(#buttonUplod).click(function () {
 $.ajaxFileUpload ({
  url:'doajaxfileupload.php', //You handle servers that upload files
  secureuri:false, //The ID value corresponding to the file in the page processing code
  fileElementId:'img',
  dataType: 'json', //Return data types :text, XML,json, HTML,scritp,jsonp
  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'=>' Uploaded successfully ');
 }
?> 


For testing, you can save the values of the passed variables in a manner 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 '));
The exit (json_encode (' file_infor = > 'upload failed '));


Does pay attention to
Notice the markup in the HTML code file box:

1. Id ='img' is used to identify the fileElementId:'img' of the ajaxfileupload.js plug-in.
2. Name ='img' is used to post to the background script, PHP through $_FILES['img'] to read the uploaded file data, if there is no this value, $_FILES variable is empty;

Therefore, these two values should not be absent, and should not be confused.

Sometimes, we need to feel the handling of the uploaded file in the background according to certain variables. For example, update the file. At this point, some additional parameters need to be passed to the same platform. 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 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 what I added. In this way, I can pass additional parameters in the foreground HTML section with code similar to the following:

Url :'doajaxfileupload.php', // you handle the server side of uploading files
Secureuri :false, // the ID value corresponding to the file in the page processing code
Data :{'test':'test','ok':'ok'}
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 ')); 

As you can see, the principle is as simple as adding the extra data object content to the form under the iframe, passing it to the background PHP script, and getting these values in variables like $_REQUEST.
The contents of file_info.txt reserved by 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,
      'the size = > In 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="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 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
     {
      $(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 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;
  }
}) 

Related articles: