1 Flares Google+ 1 Facebook 0 Twitter 0 LinkedIn 0 1 Flares ×

Image upload is simple to just select an image and click on the upload button that’s it. But it will be more effective when the selected image upload instanly means with out click on any upload button and you will see also the preview of that uploaded image.

All this will be more easy with ajax (asynchronous javaScript and xml) request. In this example we will use the ajax form plugin. I really thanks for this plugin because with the help of this plugin it will be more easy to make an ajax based instant image upload script.

Instant Image Upload



Before making this image upload script, first we have to get the file extension to detect the exact file extension.

HTML section for image upload:

<div>
    <form id="myform" action="image_uploader.php" method="post" enctype="multipart/form-data">
        <table align="center">
            <tr>
                <td width="100"><label>Select File: </label></td>
                <td>
                    <input type="file" id="myfile" name="myfile">
                </td>
            </tr>
        </table>
    </form>
</div>
<div id="result"></div>

Please don’t forget to insert the jquery library, and the ajax form plugin before starting.

Attach AjaxForm plugin:

We are using .delegate() event handler, so that our event attached with the selector now or in the future. We have to use ‘change’ event in the .delegate() event handler, so that the attached event function work just after selecting the image or file. Now just attach the ajaxForm() with submit() event which automatically call to theform action="image_uploader.php"and pass the file data to the php file:

$(function(){
    var $form = $('#myform'), 
        $result = $('#result');
                    
    $('form').delegate('#myfile', 'change', function(){
        $result.ajaxStart(function(){
            $(this).text('Loading....');
        });
        $form.ajaxForm({
            target: $result
        }).submit();
    });
               
})

PHP file that handle the FORM data

Now we have to create a PHP file that handle the data sent from the ajaxForm() plugin, so just create a php file with the name “image_uploader.php”, you can give any name according to you that you have applied into your FORM’s action attribute.

First of all collect the name, size and the temporary name of the uploaded file, this is all what we to move a file from the temporary location to the main location. During the file upload, the uploaded file temporary stored in the /tmp directory of your server, with some automatically generated name and after that its automatically deleted. During this upload process we have to move that temporary file to our main location with the same name and extension.

So, first restrict your users to spamming or validate some necessary settings for your upload like: validate the file and there size and after that we are using the move_uploaded_file() PHP’s function to move the temporary file to the our given location.

    /*
     * Image Uploader File
     * ===================
     * 
     * This file only move the uploaded images
     * to the destination folder
     */

     // Detect the file params according to need
     $filename = $_FILES["myfile"]["name"];
     $filesize = $_FILES["myfile"]["size"];
     $tmp_name = $_FILES["myfile"]["tmp_name"];
     
     
     // Valid extensions for Upload
     $validExtensions = array('.jpeg', '.jpg', '.gif', '.png');
     
     // Valid size in KB
     $max_size = 500; 
     
     // Detect file extension
     $extension = strtolower(strrchr($filename, "."));
     
     // Convert filesize in KB
     $getFileSize = round($filesize / 1024, 1);
     
     // Location to store the file
     $path = str_replace('\/\\', '/', dirname(__FILE__)) . "/image/";
     
     if( in_array($extension, $validExtensions) ){
         
         if( $getFileSize < $max_size ){
             
             if(is_dir($path)){
                 
                 move_uploaded_file($tmp_name, "$path/$filename");
            
                echo '
                    <ul class="thumbnails">
                        <li class="span4"></li>
                        <li class="span4">
                            <a href="#" class="thumbnail">
                            <img src="image/'.$filename.'" />
                            </a>
                        </li>
                    </ul>';
             } else {
                 trigger_errors("Directory not Found!<br /> $path");
             }
            
         } else {
             $error_msg = "<strong>Filesize should be less then $max_size KB!</strong><br />Your file is about $getFileSize KB";
             trigger_errors($error_msg);
         }
         
     } else {
         $error_msg = "<strong>File not Supproted for Upload!</strong><br />
                        Please try with the files that has following extensions: .jpg, .jpeg, .gif, .png";
         trigger_errors($error_msg);
     }
     
     // Make function that 
     // generate the Error
     function trigger_errors( $error_msg ){
         echo "<div class='alert alert-error'>
             <button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button>
             $error_msg
             </div>";
     }

About the author

Jogesh Sharma Jogesh Sharma is a web developer and blogger who loves all the things design and the technology, He love all the things having to do with PHP, WordPress, Joomla, Magento, Durpal, Codeigniter, jQuery, HTML5 etc. He is the author of this blog. If you'd like to connect with him, head on over the Google+