How to upload file using JavaScript and PHP

Kailash Singh

How to upload file using JavaScript and PHP

Published Oct 24,2020 by Kailash Singh

0 Comment     1268 Views    


In this tutorial, we are going to learn about how to upload file using JavaScript and PHP.

 

Step 1 :- Create HTML in index.php file

 

In this file, create a input file field and a button. Add a onclick event on the button which calls uploadData() function.

 

<input type="file" name="file" id="file" class="form-control">

<button type="button" class="btn btn-primary btn-lg" onclick="uploadData();" >Upload</button>

 

Step 2 :- Create JavaScript in index.php file

 

<script type="text/javascript">
function uploadData() {

  //get input file value
   var content = document.getElementById("file").files;

   if(content.length > 0 ){

      var formData = new FormData();
      formData.append("file", content[0]);

      var xhttp = new XMLHttpRequest();

      // ajax file path and Set POST method
      xhttp.open("POST", "fileUpload.php", true);

      // call on request on ready changes state
      xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {

           var response = this.responseText;
           if(response == 1){
              alert("Upload File Successfully.");
           }else{
              alert("File Not Uploaded Successfully.");
           }
         }
      };

      // Send request with data
      xhttp.send(formData);

   }else{
      alert("Please Select A File");
   }

}
</script>

 

Step 3 :- Create another file fileUpload.php file.

 

Create a fileUpload.php file an upload folder to store file.

 

<?php

if(isset($_FILES['file']['name'])){
   //Get file name
   $filename = $_FILES['file']['name'];

   // Set File Location
   $file_location = 'upload/'.$filename;

   // file extension
   $file_extension = pathinfo($file_location, PATHINFO_EXTENSION);
   $file_extension = strtolower($file_extension);

   //Check Valid extensions
   $check_extension = array("jpg","png","doc","docx","pdf","jpeg");

   $response = 0;
   if(in_array($file_extension,$check_extension)){
      // Upload file
      if(move_uploaded_file($_FILES['file']['tmp_name'],$file_location)){
         $response = 1;
      } 
   }

   echo $response;
   exit;
}

?>

 

Hope this will help our developers.


Comments ( 0 )