KenoKivabe

Your Essential Queries

Author
Makitweb
23 Jul, 2022

Upload A File Using jQuery and Ajax

Using PHP move_uploaded_file() function we can easily upload a file to our server

1. HTML

Create a <form> element first, which will contain a file <input>, a submit <button> and a <img> for image preview

  1. <div class="container">  
  2.     <form method="post" action="" enctype="multipart/form-data" id="myform">  
  3.         <div class='preview'>  
  4.             <img src="" id="img" width="100" height="100">  
  5.         </div>  
  6.         <div >  
  7.             <input type="file" id="file" name="file" />  
  8.             <input type="button" class="button" value="Upload" id="but_upload">  
  9.         </div>  
  10.     </form>  
  11. </div>  


2. CSS

Apply these styles to form element

  1. /* Container */.container{  
  2.    margin: 0 auto;  
  3.    border: 0px solid black;  
  4.    width: 50%;  
  5.    height: 250px;  
  6.    border-radius: 3px;  
  7.    background-color: ghostwhite;  
  8.    text-align: center;  
  9. }  
  10. /* Preview */.preview{  
  11.    width: 100px;  
  12.    height: 100px;  
  13.    border: 1px solid black;  
  14.    margin: 0 auto;  
  15.    background: white;  
  16. }  
  17.   
  18. .preview img{  
  19.    display: none;  
  20. }  
  21. /* Button */.button{  
  22.    border: 0px;  
  23.    background-color: deepskyblue;  
  24.    color: white;  
  25.    padding: 5px 15px;  
  26.    margin-left: 10px;  
  27. }  


3. PHP

Create a php file named upload.php where you've have to validate image file first. After validating the image store the file in a server directory/folder using move_uploaded_file() function

  1. <?php  
  2.   
  3. if(isset($_FILES['file']['name'])){  
  4.   
  5.    /* Getting file name */   $filename = $_FILES['file']['name'];  
  6.   
  7.    /* Location */   $location = "upload/".$filename;  
  8.    $imageFileType = pathinfo($location,PATHINFO_EXTENSION);  
  9.    $imageFileType = strtolower($imageFileType);  
  10.   
  11.    /* Valid extensions */   $valid_extensions = array("jpg","jpeg","png");  
  12.   
  13.    $response = 0;  
  14.    /* Check file extension */   if(in_array(strtolower($imageFileType), $valid_extensions)) {  
  15.       /* Upload file */      if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){  
  16.          $response = $location;  
  17.       }  
  18.    }  
  19.   
  20.    echo $response;  
  21.    exit;  
  22. }  
  23.   
  24. echo 0;  


4. jQuery

Use these jQuery script to trigger while clicking the upload button. Validate if any file selected or not. After validating send the file using Ajax to upload.php.

  1. $(document).ready(function(){  
  2.     $("#but_upload").click(function(){  
  3.         var fd = new FormData();  
  4.         var files = $('#file')[0].files;  
  5.           
  6.         // Check file selected or not  
  7.         if(files.length > 0 ){  
  8.            fd.append('file',files[0]);  
  9.   
  10.            $.ajax({  
  11.               url: 'upload.php',  
  12.               type: 'post',  
  13.               data: fd,  
  14.               contentType: false,  
  15.               processData: false,  
  16.               success: function(response){  
  17.                  if(response != 0){  
  18.                     $("#img").attr("src",response);   
  19.                     $(".preview img").show(); // Display image element  
  20.                  }else{  
  21.                     alert('file not uploaded');  
  22.                  }  
  23.               },  
  24.            });  
  25.         }else{  
  26.            alert("Please select a file.");  
  27.         }  
  28.     });  
  29. });  

Share: