Thursday, November 22, 2018

Image upload by ajax in php

AJAX Image upload in php

It's very simple process to image upload by AJAX . It's working fine. You can easily upload the image by AJAX. Follow the below step. Code download  Click Here
1. Create a simple .php or .html file. We have created index.php file look below




<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div><b>Upload Profile Image By AJAX</b></div><br>
 <div class="calendra-popup-box custom-pp-image">
  <label>Profile Image</label>
  <input id="avatar" type="file" name="pimage" >
  <input type="hidden" id="base" value=""><br>
         <button id="submitImage">Save</button>
 </div>
</div>
</body>
</html>

<script type="text/javascript">
jQuery('#submitImage').click(function() {
  if ($("#avatar").prop("files")[0] ) {
            var reader = new FileReader();
             reader.onload = function (e) {
      $('#avatar').attr('src', e.target.result);
      $('#base').val(e.target.result);
      //var abc = $('#base1').attr('src', e.target.result);
  var imgdata = $('#base').val();
  var dataUrl = "ajaxResponse.php";
  $.ajax({
      type: "POST",
      url: dataUrl,
      data: {
          'imgres': imgdata,
      },
      success: function(result){
         alert('image upload sucessfully in folder');
       $('#avatar').val('');
         }
  });
     };
   reader.readAsDataURL($("#avatar").prop("files")[0]);
   }else{
    alert('Please Upload Image');
   }
})
</script>




2. Second file is ajaxResponse.php. There are managing image request data. look below.

<?php
$imgresEncode = $_REQUEST['imgres'];
if($imgresEncode !=''){
    $number = rand().'_'.date('Y-m-d');
    $split = explode(',', $imgresEncode,2);
    $extArr = explode(';', $split[0]);
    $extnsnArr = explode('/', $extArr[0]);
    $extns = end($extnsnArr);
    $img = str_replace(' ', '+', $split[1]);
    $data = base64_decode($img);
    $imageName  = "image_$number.".$extns;
    $actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
    $filepath = dirname(__FILE__)."/storage/profileimage/".$imageName;
    $success = file_put_contents($filepath, $data);
}
?>

0 comments:

Post a Comment