4 February 2013

Upload File using Ajax, PHP and jquery

Hi..

I want to upload a file using Ajax, Jquery and PHP in such a way so that my page doesn't get refresh while submit the form.

But I found the solution to use the iframe, I found it little bit complex and bit tricky what about if I say you do not required the iframe to upload??

Download the sample and try your self its straight and simple, not a tricky one.

Uploader Sample..

Index page with form

<form action="uploader.php" id="FileUploader" enctype="multipart/form-data" method="post" >
    <label>Name
    <span class="small">I will add a random no.</span>
    </label>
    <input type="text" name="mName" id="mName" />
    
    <label>File
    <span class="small">Choose a File</span>
    </label>
    <input type="file" name="mFile" id="mFile" />
    <button type="submit" class="red-button" id="uploadButton">
          Upload (1MB)
    </button>
    <div class="spacer"></div>
</form>

In uploader.php we have following code -
<?php
//Upload Directory, ends with slash & make sure folder exist
$UploadDirectory = 'uploads/'; 

// checking uploading directory exist or not.
if (!@file_exists($UploadDirectory)) {
 //if destination folder does not exist
 die("Make sure Upload directory exist!");
}

if($_POST)
{ 
 if(!isset($_POST['mName']) || strlen($_POST['mName'])<1){
  //required variables are empty
  die("Title is empty!");
 }
 
 if(!isset($_FILES['mFile'])){
  //required variables are empty
  die("File is empty!");
 }

 
 if($_FILES['mFile']['error']){
  //File upload error encountered
  die(upload_errors($_FILES['mFile']['error']));
 }
 
 //uploaded file name, extension, type, size and a random number
 $FileName  = strtolower($_FILES['mFile']['name']); 
 $ImageExt  = substr($FileName, strrpos($FileName, '.'));
 $FileType  = $_FILES['mFile']['type'];
 $FileSize  = $_FILES['mFile']["size"];
 $RandNumber    = rand(0, 9999999999);
  
 
 switch(strtolower($FileType))
 {
  //allowed file types
  case 'image/png': //png file
  case 'image/gif': //gif file 
  case 'image/jpeg': //jpeg file
  case 'application/pdf': //PDF file
  case 'application/msword': //ms word file
  case 'application/vnd.ms-excel': //ms excel file
  case 'application/x-zip-compressed': //zip file
  case 'text/plain': //text file
  case 'text/html': //html file
  case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': //html file
   break;
  default:
   die('Unsupported File!'); //output error
 }

  

   //Rename and save uploded file to destination folder.
   $NewFileName = $_POST['mName'].'_'.$RandNumber.$ImageExt;

 if(move_uploaded_file($_FILES['mFile']["tmp_name"], $UploadDirectory.$NewFileName ))
   {  
       die('Success! File Uploaded.');
   }
   else
   {
       die('error uploading File!');
   }
}


function upload_errors($err_code)
{
  switch ($err_code)
  { 
     case UPLOAD_ERR_INI_SIZE: 
         return 'The uploaded file exceeds the upload_max_filesize directive in php.ini'; 
     case UPLOAD_ERR_FORM_SIZE: 
         return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form'; 
     case UPLOAD_ERR_PARTIAL: 
         return 'The uploaded file was only partially uploaded'; 
     case UPLOAD_ERR_NO_FILE: 
         return 'No file was uploaded'; 
     case UPLOAD_ERR_NO_TMP_DIR: 
         return 'Missing a temporary folder'; 
     case UPLOAD_ERR_CANT_WRITE: 
         return 'Failed to write file to disk'; 
     case UPLOAD_ERR_EXTENSION: 
         return 'File upload stopped by extension'; 
     default: 
         return 'Unknown upload error'; 
  } 
} 
?>

Happy Coding..


No comments:

Post a Comment