Upload files using php/ajax

Upload files in php/ajax :


Every web developer need a way so that he can upload files without refreshing the page using php . This can be achived in very simple steps.We will use asynchronous ajax method here for uploading the files in php.


Requirment:

html file : index.html
php file : transmit.php
A folder in localhost or on server where you will upload the files.







 * Html file which will contain front end file( a form ) or the main features of this file is as follows
* A input type file tag for upload file :
 This tag can me formatted in many ways it . Format the upload file tag could be little bit tricky using javascript and jquery so here is very simple css code for formating this tag you can cutomize it as you want there are many mathods available for formatting this upload button some of them you want to learn can click here.
* Html file will also contain some javascript code in javascript first thing will be checked that it is a image file or not than we can define its file size i.e the size of image or whatever we want to upload.If everything is ready than we will make ajax call for sending the data to our external php script that will upload the file on our server or to the desired location we have provided.

* Php Tranmit file :

This is the php file which will transmit the image file and its data to specific folder or server and than provide response back to ajax call in this way the whole data will transmit in two parts and the file will be uploded to server.

                             
upload file
Upload file using ajax/php



For using these files make sure you have a active internet connection because the html file contains the jquery cdn which will deliver its content only through network if you wish to use this method offline you can download jquery from jquery.com and use it.


Html file :




 <html>

  <head>

   <title>File upload php/ajax</title>

   <style>

   div{

    margin: 14% 22%;

   }

   div p{color:red;font-size:2em;}

   label{

    padding: 20px;

    background: green;

    font-size:30px;

    color: #fff;

    }

   input[type="file"] {

    display: none;

   }

   </style>

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

      <script>

         function UploadFile(event){

         var data = new FormData();                                  

         fcount = event.target.files;

         for (var i = 0; i < fcount.length; i++) {

         var file = fcount[i];

         if(!file.type.match('image.*')) {    //check if file is image or not         

         $("#status").html("Kindly upload a image or pdf file");

        }else if(file.size > 400000){    //limit here for your files in bits

         $("#status").html("Please enter a image or pdf size less than 50kb.");

      }else{

       data.append('file', file, file.name);

       //javascript ajax method call to external transmit.php file

          var xhr = new XMLHttpRequest();    

          xhr.open('POST', 'transmita.php', true); 

          xhr.send(data);

          xhr.onload = function () {

          var response = JSON.parse(xhr.responseText);

          if(xhr.status === 200 && response.status == 'success'){

          $("#status").html("Your file has been uploded successfully");

          }else if(response.status == 'Extention_error'){

          $("#status").html("please choose a image or pdf file.");

         }else{

          $("#status").html("File upload failed try another time.");

         }

        };

     }

    }

   }

   </script>

 </head>

 <body>

 <form>     

     <div>

          <p id="status">Select file to upload</p>

       <label id="#bb"> Upload Your File

       <input type="file"  onchange = 'UploadFile(event)';  size="60" />

      </label>

    </div>

   </form>

  </body>

 </html>



Tranmit.php features

* It will contains path to the folder where file will be uploded.
*It will extract the extension from the file name than it will check for file extension.
* If everything is ready than it will call move_uploaded_file() mehod of php that will upload the file on server or to specific location.
* According to the situation this file will give response to html file.



  <?php

   if(isset($_POST) == true){

     $fileName = rand().'_'.basename($_FILES["file"]["name"]);

     $targetPath = "uploads/";

     $targetFullPath = $targetPath . $fileName;

     $fileExt = pathinfo($targetFullPath,PATHINFO_EXTENSION);

     $validatefiles = array('png','gif','jpeg','jpg','pdf','Tiff');

      if(in_array($fileExt, $validatefiles)){

      if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFullPath)){

      $ajaxreply['status'] = 'success';

        }else{

            $ajaxreply['status'] = 'failed';

        }

      }else{

        $ajaxreply['status'] = 'Extention_error';

      }

      echo json_encode($ajaxreply);

   }

  ?>


No comments:

Post a Comment