Home >Web Front-end >JS Tutorial >Use ajaxfileupload.js to implement ajax upload file php version_jquery

Use ajaxfileupload.js to implement ajax upload file php version_jquery

WBOY
WBOYOriginal
2016-05-16 16:43:111645browse

Both PHP and other server-side scripts provide the file upload function, and it is relatively simple to implement. Using JavaScript to cooperate, you can implement Ajax file upload. Although jQuery itself does not provide such a simplified function, there are many plug-ins that can achieve it. Among them, ajaxfileupload.js provided by Phpletter.com is a lightweight plug-in, and its writing method is very similar to the global method $.post() provided by jQuery, which is simple and easy to use.
However, the plug-in is too simplified. In addition to providing the path of the file to be uploaded, it cannot pass additional values ​​to the backend server. So, I modified the script and added a data object parameter.

1. Principle

I am using PHP as the server script here. Almost every PHP-less book will mention how to use the move_uploaded_file() method to upload files, so I won’t go into details here. What I want to say is, use the principle of Ajax upload.
Because I have been using the jQuery library, when I think of Ajax, my first reaction is to try the $.post() method, use each selector to get the value in the file file box, and then submit it to the background server. Of course, it turned out later that this didn't work. (Because of this problem, I also checked a lot of information, and there are many ASP and other scripts available online. I really don’t know what to say.)
Back to the topic, it is not difficult to implement Ajax upload, and there are many methods. The ajaxfileupload.js plug-in of Phpletter.com mentioned in this article uses iframe. This is also a common method to achieve uploading without refreshing the page when not using JavaScript scripts. (This blog uses this method to write logs in the background of bo-blog)
The ajaxfileupload.js plug-in is also very simple. It first uses jQuery's selector to obtain the file path value in the file upload box, then dynamically creates an iframe, and creates a new file box in it, providing a post method to submit to Backstage. Finally, return the results to the front desk.

2. Use

Using the ajaxfileupload.js plug-in is very simple.
The frontend HTML code is similar:

<script type="text/javascript">
$(#buttonUplod).click(function () {
 $.ajaxFileUpload ({
  url:'doajaxfileupload.php', //你处理上传文件的服务端
  secureuri:false, //与页面处理代码中file相对应的ID值
  fileElementId:'img',
  dataType: 'json', //返回数据类型: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> 

Backend doajaxfileupload.php script:

<&#63;php
 $upFilePath = "../attachment/";
$ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);
 if($ok === FALSE){
  echo json_encode('file_infor'=>'上传失败');
 }else{
  echo json_encode('file_infor'=>'上传成功');
 }
&#63;> 


For testing, you can save the passed variable value 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'=>'Upload successful'));
exit (json_encode('file_infor'=>'Upload failed'));


※ Note
Please note the tag 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 will use this string to obtain the value of the text box;
2. name='img' is used when submitting to the background script through post. PHP reads the data of the uploaded file through $_FILES['img']. If there is no such value, the $_FILES variable is empty;

So, these two values ​​are indispensable and cannot be confused.

3. Support additional parameters

Sometimes, we need to process uploaded files based on certain variables in the background. For example, update files. At this time, you need to pass some additional parameters to the same stage. 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 marked part is the content I added. In this way, I can pass additional parameters in the frontend HTML part through code similar to the following:

url:'doajaxfileupload.php', //Your server that handles uploaded files
secureuri:false, //ID value corresponding to file in the page processing code
data:{'test':'test','ok':'ok'}, //Transmitted as an object, JavaScript variable values ​​can be entered in the content part
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'=>'上传成功'));
exit (json_encode('file_infor'=>'上传失败')); 

It can be seen that the principle is very simple, that is, add the additional data object content to the form under the iframe, pass it to the background PHP script, and obtain these values ​​​​with variables such as $_REQUEST.
The content of file_info.txt retained 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,
'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="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&#63;io.contentWindow.document.body.innerHTML:null;
 xml.responseXML = io.contentWindow.document.XMLDocument&#63;io.contentWindow.document.XMLDocument:io.contentWindow.document;
  }else if(io.contentDocument)
  {
   xml.responseText = io.contentDocument.document.body&#63;io.contentDocument.document.body.innerHTML:null;
 xml.responseXML = io.contentDocument.document.XMLDocument&#63;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" &#63; "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 &#63; 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;
  }
}) 
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn