English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP+Ajax Asynchronous File Upload with Progress Bar Example

In the recent project, I need to implement a file upload function with a progress bar. I learned about Ajax, which is quite convenient to use, and it can be achieved by implementing several methods.

Front-end file inclusion

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

Ajax progress bar asynchronous processing

<script type="text/javascript">
$(function () {
   $("#myupload").ajaxForm({
     dataType:'json',
     beforeSend:function(){ 
         $(".progress").show();
     ,
     uploadProgress:function(event,position,total,percentComplete){
         var percentVal = percentComplete + %'");
         $(".progress-bar").width(percentComplete + '%');
         $(".progress-bar").html(percentVal);
         $(".sr-only").html(percentComplete + '%');
     ,
     success:function(data){
         $(".progress").hide();
         if(data.error == "empty_name"){
             alert("Illegal file upload, upload failed!");
             exit();
         });
         if(data.error == "large"){
             alert("Image upload cannot exceed2M, upload failed!");
             exit();
         });
 /*alert(data.error);*/
         if(data.error == "format"){
             alert("Image format error, upload failed");
             //alert(data.type);
             exit();
         });
         //alert("Upload successful!");
         //files.html("<b"+data.name+"("+data.size+"k)</b> <span class='delimg' rel='"++"'>delete</span>");
         $(".files").html("Filename: "+data.name+"<span class='delimg' rel='"++"'>  delete  </span>Size:"+data.size);
         var img = "http://www.sandleft.com/test/input/upload/files/"+data.pic;
         $(".showimg").html("<img src='"+img+"'>");
         alert("Upload successful!");
     ,
     error:function(){
         alert("Image upload failed");
     }
   });
   $(".progress").hide();
});
</script>

front-end uploads HTML

<div class="uk-container uk-container-center">
        <div class="pk-system-messages"></div>
        <h1 class="uk-h2 uk-text-center" style="margin-top:-100px;">File upload</h1>
        <div class="pk-system-messages"></div>
         <div class="container-main">
          <h1>Ajax Image Uploader</h1>
          <p>A simple tutorial to explain image uploading using jquery ajax and php</p>
           <form id='myupload' action='new_upload.php' method='post' enctype='multipart/form-data'>
            <label for="file">Filename:</label>
           <input type="file" name="mypic" id="file"><br>
           <input type="submit" name="upload" class="btn btn-success" value="upload">
          </form>
            <div class="progress">
             <div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
              <span class="sr-only">0% Complete</span>
           </div>
           </div>
          <div class="files"></div>
          <div class="showimg"></div>
         </div>
       </div>

PHP file upload class

<?php
class upload{
  protected $file_path = "files"; //Current files storage folder
  #protected $file_size = 1024000;
  protected $file_size = 5120000; //5M User upload
  //Check if the file is empty
 public function check_file($get_file)
 {
    if (empty($get_file))}}
    {
     $type = "check_file";
       $arr = array('error'=>'empty_name','type'=>$type);
       echo json_encode($arr);
       exit();
    }
  return true;
}
 //File type detection
 public function check_type($get_type)
 {
   if (( $get_type == ".docx" ) || ( $get_type == ".doc" )) {
      #$types = $get_type;
   }else{
      $type = "check_type";
      $arr = array('error'=>'format','type'=>$type);
        echo json_encode($arr);
        exit(); 
   }
  return true;
 }
 //File size detection
 public function check_size($get_file)
 {
   if ( $get_file != "" ) {
      if ( $get_file > $this->file_size ) {
          $arr = array('error'=>'large');
          echo json_encode($arr);
          exit();
      }
  }else{
    return false;
    exit();
  }
 return true;
 }
//File saving
 public function save_file($file_type,$file_tmp_name)
 {
  $rand = rand(1000, 9999);
  $pics = date("YmdHis") . $rand . $file_type;
  $path = $this->file_path."/".$pics;
  $result = move_uploaded_file($file_tmp_name, $path);
  if($result){
    return $pics;
  }else{
    return false;
    exit();
  }
  #return $pics;
 }
}
PHP file upload processing
<?php
include("upload.class.php");
$up_obj = new upload();
$get_fileName = $_FILES['mypic']['name'];
$get_fileSize = $_FILES['mypic']['size'];
$get_TmpFiles = $_FILES['mypic']['tmp_name'];
$get_fileType = strstr($get_fileName, '.');
$check_result = $up_obj->check_file($get_fileName);
if($check_result){
  //Check the file type
  $result_type = $up_obj->check_type($get_fileType);
  //Check the file size
  if($result_type){
    $result_size = $up_obj->check_size($get_fileSize);
    if($result_size){
      //File upload and save  
      $pics = $up_obj->save_file($get_fileType,$get_TmpFiles);   
      $size = round($get_fileSize/1024,2);
          $arr = array(
            'name' => $get_fileName,
             'pic' => $pics,
             'size' => $size,
             'error' => 2
         );
       //Check the file upload status
       if($pics){
         echo json_encode($arr);
         /*
         Execute the upload completion logic.....
         */
      }   
    }
  }
}

The effect of file upload is shown in the figure:

That's all for this article. I hope it will be helpful to everyone's learning and that everyone will support the Shouting Tutorial more.

Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like