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

May 16, 2016 pm 04:43 PM
ajax upload files

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> 
Copy after login

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

Copy after login


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

Copy after login

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'=>'上传失败')); 

Copy after login

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;
  }
}) 
Copy after login
Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to upload files to 123 cloud disk How to upload files to 123 cloud disk Feb 24, 2024 pm 05:30 PM

How to upload files to 123 Cloud Disk? You can upload files to 123 Cloud Disk for storage, but most friends don’t know how to upload files to 123 Cloud Disk. Next is the picture and text of how to upload files to 123 Cloud Disk brought by the editor for players. Tutorial, interested users come and take a look! How to upload files on 123 Cloud Disk 1. First open 123 Cloud Disk and enter the main page, register or log in to the account; 2. Then enter the page as shown below, click the [Upload] button guided by the arrow; 3. Then the bottom will expand In the function bar window, click the [Select File] function; 4. Finally, select the file to be uploaded and wait patiently for the upload to complete.

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles