How to upload Image file using AJAX and jQuery

In PHP you can easily upload any type file on the server using the move_uploaded_file() method.
But it requires form submit for uploading the selected file.
If you want to store image file and display preview without reloading the whole page then you need to use jQuery AJAX.
Send the selected file using the FormData object in AJAX request.

Contents

  1. HTML
  2. CSS
  3. PHP
  4. jQuery
  5. Conclusion

1. HTML

Create a <form > element where added <img >, file element and a button.
Image preview display in <img> after successfully upload using jQuery.

Completed Code

<div class="container">
    <form method="post" action="" enctype="multipart/form-data" id="myform">
        <div class='preview'>
            <img src="" id="img" width="100" height="100">
        </div>
        <div >
            <input type="file" id="file" name="file" />
            <input type="button" class="button" value="Upload" id="but_upload">
        </div>
    </form>
</div>
 

2. CSS

Hide the img element.

/* Container */
.container{
   margin: 0 auto;
   border: 0px solid black;
   width: 50%;
   height: 250px;
   border-radius: 3px;
   background-color: ghostwhite;
   text-align: center;
}
/* Preview */
.preview{
   width: 100px;
   height: 100px;
   border: 1px solid black;
   margin: 0 auto;
   background: white;
}

.preview img{
   display: none;
}
/* Button */
.button{
   border: 0px;
   background-color: deepskyblue;
   color: white;
   padding: 5px 15px;
   margin-left: 10px;
}
 
 

3. PHP

Create an upload.php file and upload directory for storing image files.
Check the file extension if it is valid then store the file and return the file location.

Completed Code

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = "upload/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);

/* Valid Extensions */
$valid_extensions = array("jpg","jpeg","png");
/* Check file extension */
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
   $uploadOk = 0;
}

if($uploadOk == 0){
   echo 0;
}else{
   /* Upload file */
   if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
      echo $location;
   }else{
      echo 0;
   }
}
 

4. jQuery

On the upload button click get the selected file and create a FormData object.
Append file in FormData object.
Send an AJAX request where pass the fd object and on successful callback check the response is 0 or not.
If it does not 0 then update the <img > source otherwise alert('file not uploaded') message.
On page load img element is set display: none;.
This element is getting displayed when a file is successfully uploaded with jQuery – $(".preview img").show();.


Completed Code
 
$(document).ready(function(){

    $("#but_upload").click(function(){

        var fd = new FormData();
        var files = $('#file')[0].files[0];
        fd.append('file',files);

        $.ajax({
            url: 'upload.php',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                    $("#img").attr("src",response); 
                    $(".preview img").show(); // Display image element
                }else{
                    alert('file not uploaded');
                }
            },
        });
    });
}); 
 
 

5. Conclusion

Use FormData object to store the file and pass in the AJAX request to upload it.
In the PHP file access the file using $_FILES.
 
 

 
 

 


CONVERSATION

0 Comments:

Post a Comment

Back
to top