Upload and delete image file with jQuery and AJAX

With the use of AJAX, you can easily upload the selected file to your server and show a preview of it.

If you like to add a remove button to delete the file without page load then you again need to use AJAX to remove the file from the server.

I am using PHP to handle AJAX request on the server-side.

Upload and delete image file with jQuery and AJAX


Contents

  1. HTML
  2. PHP
  3. Script
  4. Output
  5. Conclusion

1. HTML

Create a <form > with file and button element.

Show the preview with delete button after upload in <div class='container'> using jQuery.

Completed Code

<form method="post" action="" enctype="multipart/form-data" id="myform">
 
   <input type="file" id="file" name="file" />
   <input type="button" class="button" value="Upload" id="but_upload">
 
</form>
 
<!-- Image element container -->
<div class="container"></div>

2. PHP

Create a new addremove.php file and upload folder.

Upload file

If $request == 1 then check the file extension and store the file in the upload directory.

Delete file

If $request == 2 then pass the POST source path in unlink() method to delete the file.

Completed Code

<?php
$request = $_POST['request'];

// Upload file
if($request == 1){
     $filename = $_FILES['file']['name'];
    /* Location */
    $location = "upload/".$filename;
    $uploadOk = 1;
    $imageFileType = pathinfo($location,PATHINFO_EXTENSION);

    // Check image format
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
     && $imageFileType != "gif" ) {
         $uploadOk = 0;
    }

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

// Remove file
if($request == 2){

    $path = $_POST['path'];
    $return_text = 0;

    // Check file exist or not
    if( file_exists($path) ){
       // Remove file
       unlink($path);
     
       // Set status
       $return_text = 1;
    }else{
       // Set status
       $return_text = 0;
    }

    // Return status
    echo $return_text;
    exit;
}

3. Script

File Upload 

On upload button click create a FormData Class object and append the file selected from the file element in it. Also, append request with 1 value.

Send an AJAX request where the pass FormData object.

On successful callback, if response is 1 then count the total <div class='content'> container and increment with 1. Create new <div class='content'> and use the count value to create id. Within the <div > create <img > with response value and <span > element.

Delete file using AJAX

To remove an image bind the click event on the class='delete'.

On click select the image source and display confirmation alert.

If OK button gets clicked then send an AJAX request where pass the path with a request: 2.

If response is 1 on successful callback then remove the <div > container.

Completed Code

$(document).ready(function(){

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

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

      // AJAX request
      $.ajax({
          url: 'addremove.php',
          type: 'post',
          data: fd,
          contentType: false,
          processData: false,
          success: function(response){
               if(response != 0){
                    var count = $('.container .content').length;
                    count = Number(count) + 1;

                    // Show image preview with Delete button
                    $('.container').append("<div class='content' id='content_"+count+"' ><img src='"+response+"' width='100' height='100'><span class='delete' id='delete_"+count+"'>Delete</span></div>");
               }else{
                    alert('file not uploaded');
               }
          }
      });
  });

  // Remove file
  $('.container').on('click','.content .delete',function(){
 
      var id = this.id;
      var split_id = id.split('_');
      var num = split_id[1];

      // Get image source
      var imgElement_src = $( '#content_'+num+' img' ).attr("src");
      var deleteFile = confirm("Do you really want to Delete?");
      if (deleteFile == true) {
           // AJAX request
           $.ajax({
               url: 'addremove.php',
               type: 'post',
               data: {path: imgElement_src,request: 2},
               success: function(response){
                   // Remove
                   if(response == 1){ 
                        $('#content_'+num).remove(); 
                   } 
               } 
           }); 
      } 
  }); 
});

4. Output

View Output


5. Conclusion

Use FormData object variable to send file value to AJAX file for store to the server and with unlink() method delete the file.

If you found this tutorial helpful then don't forget to share.