AJAX IMAGE UPLOADING.....

1. index.php
<body>
    <span id="msg" style="color:red"></span><br/>
    <input type="file" id="photo"><br/>
  <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      $(document).on('change','#photo',function(){
        var property = document.getElementById('photo').files[0];
        var image_name = property.name;
        var image_extension = image_name.split('.').pop().toLowerCase();

        if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
          alert("Invalid image file");
        }

        var form_data = new FormData();
        form_data.append("file",property);
        $.ajax({
          url:'upload.php',
          method:'POST',
          data:form_data,
          contentType:false,
          cache:false,
          processData:false,
          beforeSend:function(){
            $('#msg').html('Loading......');
          },
          success:function(data){
            console.log(data);
            $('#msg').html(data);
          }
        });
      });
    });
  </script>
</body>

2.upload.php
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;

$location = 'uploads/'.$name;

 //    if (!file_exists($location)) {
 //        mkdir($location, 0777, true);
 //        $myfile = fopen($location . "/index.html", "w");
 //        fclose($myfile);
 //    }
move_uploaded_file($_FILES['file']['tmp_name'], $location);

echo '<img src="'.$location.'" height="100" width="100" />';

}

Comments

Post a Comment

Popular posts from this blog

WP register_post_type() with custom CMB2 meta box

Git post receive setup at server for git push to the production from local machine