Ajax Image Uploader

  • Ajax Image Uploader.

    Ajax image uploader is a tool that allows the user to upload images and also having full functionality of the uploaded images with out using a database. This tool is developed with PHP , jQuery and CSS. Ah and a bit of bootstrap ;)

    The Javascript

    One basic document ready event to render the url fields and to get the list of the images.

                                    $(document).ready(function () {
                                        getImages();
                                        renderCasinoUrlContainers();
                                    });
                                

    The URL fields are rendered from a jSON file that stand as the APP configuration.

    function renderCasinoUrlContainers() {
    $.getJSON("config/config.json", function (data) {
        var urlList = [];
        $.each(data, function (key, val) {
            console.log(val.casinoName);
            urlList.push('<div class="url-container marginBottom">' +
                                    '<label for="js-url">' + val.casinoName + '</label>' +
                                    '<input type="text" class="form-control url-container-textbox" id="' + val.htmlId + '" aria-describedby="basic-addon3" readonly>' +
                                    '</div>');
        });
        urlList = urlList.join("");
        $(".url-control-container").html(urlList);
        $(".url-container-textbox").on("focus", function () {
            $(this).select();
        })
    });
    }
                                

    getImages() function sends the call to the PHP script and get a json response containing the image files

    function getImages() {
    /*straight forward ajax call*/
    $.ajax({
    /*content of the PHP file will be reviewed later*/
    url: 'Controllers/gallery_helper.php',
    data: {format: 'json'},
    type: 'POST',
    error: function () {
    alert("something went wrong contact the admin");
    },
    dataType: 'json',
    success: function (response) {
    /*check the json response if is empty*/
    if (response.files === null || response.files === "") {
        $(".gallery-container").html("Folder is empty");
    }
    else {
        var resultList = [];
        /*loop inside the response.files which is an array*/
        $.each(response.files, function (index) {
            /*start inserting the html containing the results from the json response */
            resultList.push(
                '<div class="col-md-3 col-xs-4 image-container-full">' +
                            '<div class="thumbnail">' +
                                '<img class="image-gallery-item" alt="100%x200" value="' + response.files[index] + '" src="u/' + response.files[index] + '" data-holder-rendered="true" />' +
                                '<div class="caption">' +
                                    '<h5>Label</h5>' +
                                    '<p class="image-description">Description</p>' +
                                    '<p><span value="' + response.files[index] + '" class="glyphicon glyphicon-remove remove-image" aria-hidden="true"></span> <span value="' + response.files[index] + '" class="glyphicon glyphicon-search get-img-url" aria-hidden="true"></span></p>' +
                                    '</div>' +
                                '</div>' +
                            '</div>');
        });
        resultList = resultList.join("");
        /*render the response inside the html container*/
        $(".gallery-container").html(resultList);
        $(".image-container-full").hide();
        /*make a fadeIn() animation with delay in each image*/
        $(".image-container-full").each(function (i) {
            $(this).delay(i * 300).fadeIn();
        });
    }
    },
    });
    }
                                

    Image Upload

    $("input[name='image_upload']").on("click", function (e) {
        $('form').ajaxForm({
            beforeSend: function(){
                /*some extra features to make the application more user friendly.*/
                /*on beforeSend state replace the canvas picture with a spinning loader gif */
                $("#preview-container").prop("src","/web-components/ImageUpload/images/loading_spinner.gif");
                /*also in the same state make the upload button disabled in case the response take time and user starts raging! */
                $("#image_upload").prop("disabled",true);
            },
            success: function (response) {
                var serverResponse = $.parseJSON(response);
                if (serverResponse.status === "OK") {
                    $.getJSON("config/config.json", function (data) {
                        $.each(data, function (key, val) {
                            /*renders the file name inside the url box*/
                            $("#" + val.htmlId).val(val.url + serverResponse.filename);
                        });
                    });
                    $(".result-container").fadeIn();
                    /*restore the controls to their original state*/
                    $("#preview-container").prop("src","empty-image-placeholder.png");
                    $("#image_upload").prop("disabled",false);
                    /*renders again the images*/
                    getImages();
                }
                else {
                    $(".no-image-error").css({"display": "block"});
                    $(".no-image-error").html('<div class="alert alert-danger" role="alert">' +
                                        '<strong>Oh snap!</strong>Please select an image.' +
                                        '</div>');
                    $("#image_upload").prop("disabled", true);
                }
            }
        });
    });
                                

    Image Preview and validation checks

      /*this event occurs when the label of the selected file name is changing meaning you have selected an image*/
    $("#images").on("change", function () {
        var inputType = $("#images");
        var extension = inputType.val().split('.').pop().toUpperCase();
        /*check if the file name has the allowed extension*/
        if (extension != "PNG" && extension != "JPG" && extension != "GIF" && extension != "JPEG") {
            $(".no-image-error").css({"display": "block"});
            $(".no-image-error").html('<div class="alert alert-danger" role="alert">' +
                                        '<strong>Oh snap!</strong> Select a valid image(PNG , GIF, JPG , JPEG)' +
                                        '</div>');
            $('#image_upload').prop('disabled', true);
        } else {
            $(".no-image-error").css({"display": "none"});
            $('#image_upload').prop('disabled', false);
            /*calls the function to set the image preview*/
            readURL(this);
        }
    });
                                
    function readURL(input) {
        if (input.files && input.files[0]) {
            var imageSize = input.files[0].size / 1024;
            /*size validation with js */
            var maxImageSize = 512;
    
            if (imageSize > maxImageSize) {
                $(".no-image-error").css({"display": "block"});
                $(".no-image-error").html('<div class="alert alert-danger" role="alert">' +
                                        '<strong>Oh snap!</strong>Sorry ... to large image' +
                                        '</div>');
                $("#image_upload").prop("disabled", true);
            }
            else {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('#preview-container').attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
    }
                                

    The PHP

    Image upload script PHP with server side validations.

    $data = array();
    if (isset($_POST['image_upload']) && !empty($_FILES['images'])) {
    
        $image = $_FILES['images'];
        $allowedExts = array("gif", "jpeg", "jpg", "png");
    
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    
        //create directory if not exists
        if (!file_exists('u')) {
            mkdir('u', 0777, true);
        }
        $image_name = $image['name'];
        //get image extension
        $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        $imageName = basename($image_name, $ext);
        //assign unique name to image
        $name = $imageName . time() . "." . $ext;
        //image size calcuation in KB
        $image_size = $image["size"] / 1024;
        $image_flag = true;
        //max image size
        $max_size = 512;
        if (in_array($ext, $allowedExts) && $image_size < $max_size) {
            $image_flag = true;
        } else {
            $image_flag = false;
            $result = array("status" => "Error", "Message" => "Choose a smaller image");
            echo json_encode($result);
        }
    
        if ($image["error"] > 0) {
            $image_flag = false;
        }
    
        if ($image_flag) {
            move_uploaded_file($image["tmp_name"], "u/" . $name);
            $src = "/u/" . $name;
            $data['success'] = $thumbnail = 'thumbnail_' . $name;
    
            /*create the json for the success state*/
            $result = array("status" => "OK",
                "imageName" => $name,
                "filename" => $src
            );
            /* DATABASE LOGIC*/
        }
        /* CLOSE DB CONNECTION*/
         /*return the success json*/
        echo json_encode($result);
    } else {
        /*return json response in case of error*/
        $result = array("status" => "Error", "Message" => "Choose a smaller image.");
        echo json_encode($result);
    }
                                

    PHP get files from folder

                                    $files = array();
    $directory = "your directory";
    
    $images = glob($directory."*.{jpg,JPG,jpeg,JPEG,png,PNG}", GLOB_BRACE);
    foreach($images as $image)
    {
        $files[] = basename($image);
    }
    echo json_encode(array("status" => "OK", "files"=>$files, "dir"=>$directory));
                                

    PHP remove file from folder

    $file = $_POST["file"];
    $filePath = "your directory" . $file;
    
    if (!unlink($filePath)) {
        echo json_encode(array("status" => "Error"));
    } else {
        echo json_encode(array("status" => "OK", "$file"));
    }
                                

    The HTML

    For more html details check the demo page or download.

    <form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post"
          action="ajax.php">
        <div class="form-group">
            <p>Please Choose Image: </p> <input class='file' type="file" class="form-control" name="images" id="images"
                   placeholder="Please choose your image">
            <span class="help-block"></span>
            </div>
        <div class="form-group">
            <img id="preview-container" src="empty-image-placeholder.png" alt="your image"/>
        </div>
        <input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
        <div class="no-image-error"></div>
    </form>
    

  • Category

Up Next

Js Metro Tabs

Alexabdros Okkalides

Magic The Gathering Slider

Alexandros Okkalides

Js-Toolbar

Alexandros Okkalides

Ajax Image Uploader

Alexandros Okkalides