Just Simple Info

Pages

Upload Image with Php and Javascript

Upload image using javascript and  jquery
I spend a lot of time to create a code that will upload image to server. Search and search and test that what I have to do to make such function worked. Luckily found something!!! Modify some codes and finally image uploaded to server. But every time I upload the whole page refresh.

I need Javascript!!!

Another time consuming searching and testing again. But after the day I did it. Code worked perfectly according to what I want.

This time we will upload image using PHP with JQuery and native Javascript.

Below is our simple Html.


<html>
    <head>
        <script type="text/javascript" src="js/jquery.js"></script>
    </head>
    <body>
        <input type="file" id ="file" name="files" accept="image/*"/>
        <button onclick="uploadImageWithNoJQuery()">Upload With No JQuery</button>
        <button id="upload" >Upload With JQuery</button>
 <br>
 <span id="status"></span>    
    </body>
</html>

We already added to head tag the jquery.js.

Here the function to upload image with just native Javascript code.

    /**
     * Upload with no jquery
     *
     */
    function uploadImageWithNoJQuery() {
       
        //*** URL
         var url = "upload.php";
         
        //*** GET FILE
        var image = document.getElementById("file").files[0];
        
        //*** CREATE FORM DATA
        var formdata = new FormData();
        //*** APPEND IMAGE TO FORM DATA OBJECT
        formdata.append("file1",image);
        
        //*** CREATE new XMLHttpRequest
        var request = new XMLHttpRequest();
        
        // EVENT LISTENER         
        request.upload.addEventListener("progress",progressHandler, false);
        request.addEventListener("load",completeHandler, false);
        request.addEventListener("error",errorHandler, false);
        request.addEventListener("abort",abortHandler, false);
                    
        //*** OPEN REQUEST 
        request.open("POST",url);
        //*** SEND
        request.send(formdata);
        
    }

Here the function to upload image with JQuery.

    /**
     * Upload using query
     */
    function uploadUsingJQuery() {
        var url = "upload.php";
       //*** GET FILE
        var image = $("#file")[0].files[0];
        
        //*** CREATE FORM DATA
        var formdata = new FormData();
        //*** APPEND IMAGE TO FORM DATA OBJECT
        formdata.append("file1",image);
        
                
                
        var ajax = $.ajax({
  url: url,
  type: 'POST',
   //**** CUSTOM PROGRESS EVENT
   xhr: function() {
       myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){
         myXhr.upload.addEventListener('progress',progressHandler, false);
         myXhr.upload.addEventListener('load',completeHandler, false);
         myXhr.upload.addEventListener('error',errorHandler, false);
         myXhr.upload.addEventListener('abort',abortHandler, false);
             }
           return myXhr;
                },
                
  data: formdata,
  processData: false, //*** IMPORTANT
  contentType: false, //*** IMPORTANT
  success: function(return_data) {
                    alert("success"+return_data);
  },
  beforeSend: function() {
      console.log('started');
  },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log(errorThrown);
      console.log(textStatus);
      
  },
  complete : function(){
      console.log('end');
  }});
       
    }

We will also provide some event listener such as progress, load, error and abort.

Here is our event handler function.

    /**
     * Progress
     */
    function progressHandler(event){
        var loaded = event.loaded;
        var total = event.total;
        var percent = Math.round((loaded / total) * 100);
        console.log(percent);
        $('#status').html(percent+" %");
    }
    /**
     * Complete
     */
    function completeHandler(event){
    //*** GET RESPONSE TEXT FROM PHP
        var response = event.target.responseText;
 
        $('#status').html("100 % successful");
    }
    /**
     * Error
     */
    function errorHandler(event){
        $('#status').html('upload error');
    }
    /**
     * Abort
     */
    function abortHandler() {
        $('#status').html('upload aborted');
    }

Here our Php file the will handle uploading image to our server.

<?php
$fileName = $_FILES['file1']['name'];
$fileTmlLoc = $_FILES['file1']['tmp_name'];
$fileType = $_FILES['file1']['type'];
$fileSize = $_FILES['file1']['size'];
$fileErrorMsg = $_FILES['file1']['error'];

if(move_uploaded_file($fileTmlLoc, 'uploads/'.$fileName)){
    
    echo $fileName.' upload is complete';
    
}else{
    
    echo 'move_uploaded_file function failed';
    
}
?>

And now below is the complete code.

<html>
    <head>
        <script type="text/javascript" src="js/jquery.js"></script>
    </head>
    <body>
        <input type="file" id ="file" name="files" accept="image/*"/>
        <button onclick="uploadImageWithNoJQuery()">Upload With No JQuery</button>
        <button id="upload" >Upload With JQuery</button>
 <br>
 <span id="status"></span>    
    </body>
</html>

<script>
    $(document).ready(function(){
            $("#upload").click(function(){
                
                uploadUsingJQuery()
                });
        });
    
    /**
     * Upload with no jquery
     *
     */
    function uploadImageWithNoJQuery() {
       
        //*** URL
         var url = "upload.php";
         
        //*** GET FILE
        var image = document.getElementById("file").files[0];
        
        //*** CREATE FORM DATA
        var formdata = new FormData();
        //*** APPEND IMAGE TO FORM DATA OBJECT
        formdata.append("file1",image);
        
        //*** CREATE new XMLHttpRequest
        var request = new XMLHttpRequest();
        
        // EVENT LISTENER         
        request.upload.addEventListener("progress",progressHandler, false);
        request.addEventListener("load",completeHandler, false);
        request.addEventListener("error",errorHandler, false);
        request.addEventListener("abort",abortHandler, false);
                    
        //*** OPEN REQUEST 
        request.open("POST",url);
        //*** SEND
        request.send(formdata);
        
    }
    /**
     * Progress
     */
    function progressHandler(event){
        var loaded = event.loaded;
        var total = event.total;
        var percent = Math.round((loaded / total) * 100);
        console.log(percent);
        $('#status').html(percent+" %");
    }
    /**
     * Complete
     */
    function completeHandler(event){
    //*** GET RESPONSE TEXT FROM PHP
        var response = event.target.responseText;
 
        $('#status').html("100 % successful");
    }
    /**
     * Error
     */
    function errorHandler(event){
        $('#status').html('upload error');
    }
    /**
     * Abort
     */
    function abortHandler() {
        $('#status').html('upload aborted');
    }
    
    
    /**
     * Upload using query
     */
    function uploadUsingJQuery() {
        var url = "upload.php";
        //*** GET FILE
        var image = $("#file")[0].files[0];
        
        //*** CREATE FORM DATA
        var formdata = new FormData();
        //*** APPEND IMAGE TO FORM DATA OBJECT
        formdata.append("file1",image);
        
                
                
        var ajax = $.ajax({
  url: url,
  type: 'POST',
   //**** CUSTOM PROGRESS EVENT
   xhr: function() {
      myXhr = $.ajaxSettings.xhr();
       if(myXhr.upload){
          
          myXhr.upload.addEventListener('progress',progressHandler, false);
          myXhr.upload.addEventListener('load',completeHandler, false);
          myXhr.upload.addEventListener('error',errorHandler, false);
          myXhr.upload.addEventListener('abort',abortHandler, false);
                    
          }
        return myXhr;
                },
                
  data: formdata,
  processData: false, //*** IMPORTANT
  contentType: false, //*** IMPORTANT
  success: function(return_data) {
  
     alert("success"+return_data);
  
 },
  beforeSend: function() {
      console.log('started');
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log(errorThrown);
      console.log(textStatus);
      
  },
  complete : function(){
      console.log('end');
  }});
       
    }
   
</script>

Download Source Code

Happy coding everyone...

No comments:

Post a Comment