jQuery AJAX Image Upload Thumbnail Example

Sam Deering

I’ve had quite a lot of requests for how to upload images using Ajax and show a thumbnail so I decided to do a quick demo to show you how it can be done. The Script facilitates the process of uploading an image via Ajax and using PHP to create a thumbnail, return the image source and display to the user as a thumbnail of the image uploaded. All without the page reloading. To help you understand how it works I’ve commented on a few of the key parts below.

View Demo View Project on Git

ajax-image-upload

The Upload Image Function

This function sends the image to the backend and receives back data about the uploaded image and it’s created thumbnail. It uses the ajaxFileUpload function.

uploadImage: function()
{
    var _this = this,
        $imgInput = $('#image-upload');

    this.cache.$imgPreview.hide();
    this.cache.$imgOriginal.hide();
    $('.img-data').remove(); //remove any previous image data

    $.ajaxFileUpload(
    {
        url: _this.settings.uploadImageUrl,
        secureuri: false,
        fileElementId: 'image-upload',
        dataType: "json",
        success: function(data)
        {
            console.log(data);
            _this.cache.$imgPreview.attr('src',data.thumb.img_src);
            _this.cache.$imgOriginal.attr('src',data.master.img_src);

            //show img data
            _this.cache.$imgPreview.after('<div class="img-data">'+$.objToString(data.thumb)+'</div>');
            _this.cache.$imgOriginal.after('<div class="img-data">'+$.objToString(data.master)+'</div>');
            $('#remove-image-upload').show();
        },
        error: function(xhr, textStatus, errorThrown)
        {
            console.log(xhr, textStatus, errorThrown + 'error');
            return false;
        },
        complete: function()
        {
            //hide loading image
            _this.cache.$form.find('.loading').hide();
            _this.cache.$imgPreview.show();
            _this.cache.$imgOriginal.show();
        }
    });
}

The Image Thumbnail

The image thumbnail src gets updated with the new thumbnail image src once the image has been uploaded.

<!-- Generated Image Thumbnail -->
<img alt="image preview " src="img/350x150.jpg" id="image-thumb"/>

Example Form Submit

The form data can be grabbed as normal and the thumbnail src is added to the data which is sent as part of the form submit.

submitForm: function()
{
    /* example of submitting the form */
    var $theForm = $('#submit-plugin-form'),
        formData = $theForm.serialize(); //get form data

    //include video thumb src
    formData += '&image-thumb=' + $('#image-thumb').attr('src');
    $theForm.find(':input').attr('disabled', 'disabled'); //lock form

    $.ajax(
    {
        type: "POST",
        url: 'php/submitForm.php',
        dataType: "json",
        data: formData,
        success: function(ret)
        {
            //...
        },
        error: function(xhr, textStatus, errorThrown)
        {
            console.log(xhr, textStatus, errorThrown + 'error');
            return false;
        }
    });
}

The backend PHP Script

I have written a backend script in PHP which receives an image from front end and uploads it, creates a thumbnail and returns both the master and thumb image info as JSON.
View PHP Script.

Folder Structure

The uploaded image and thumb are stored in a temp folder then when the form is submitted the images are moved and renamed into the main images folder.
folder-structure

Naming of Files

The temp files are named using a timestamp and thumbs with their dimension.
image-filenames

Security

You’ll need to make sure the images directory has writable permissions 774 should be high enough.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Pingback: Qoozon » Cool Stuff For Web Designers #7

  • http://jquery4u.com/ jQuery4u

    Hi mate, looks like a PHP error, any luck with fixing it?

  • daniel

    Hi Sam,

    I can’t upload your PHP back end file.
    Is it normal ?

    Thanks

    • http://jquery4u.com/ jQuery4u

      My PHP site is down at the moment waiting for some time to restore hopefully soon.
      Sam

  • Anonmate

    My antivirus caught a trojan when i pressed your php file view thingy.
    Also i can’t view the php code.

  • rajeswai

    i got this error

    $.ajaxFileUpload is not a function. how to fix this

    thanks

    • http://jquery4u.com/ jQuery4u

      $.ajaxFileUpload relates to the upload plugin, have you included the plugin before calling it?

      • Raj

        Yes

  • rajeswari

    how to get multiple file upload.

    • Jcrum34

      A little bit late but did u find an issue ?

      thx

  • javed

    how to download the source cod

  • kilo

    no backend php script. Please fix it.

  • Krissh

    Hi Sam Deering this was really a nice post but we haven’t find download link here…really i thanks to this tutorial

    • http://jquery4u.com/ jQuery4u

      Hi I’m going to get the code uploaded to GitHub soon for you to download, sorry about the delay.

  • Sopian A.S. Iskandar

    can i download the script please ,,

  • Ankit Jain

    Sir do you have Backend JSP script for above javascript?If yes please mail me to ankitjainpiet@gmail.com

  • lidya1859

    i’m looking for this..may i have your script?? which site i can download it?? i want to learn that..thank you.. :)

  • agung

    how can i use this as an inherited object,? i have a website that require many image upload form, so i can use it repeatedly in my website, no need to copy and modified the script for each upload form.

  • Guest

    how can i make it multiple image upload in one form?

  • efe

    cant get it to work

  • Mark

    Thanks, I have been looking for an example like this for a while.

    I got it to work, but had to change uploadImageUrl to ‘php/phpUploadImage.php’ in js/jquery-ajax-image-upload.js.

    Thanks again!

  • Jcrum34

    Hey ! Nice job !
    Is it possible to have multiple image upload in the same form ?
    thx a lot !

    • Love IT

      Call name input like array.
      example:

  • http://johanfjr.blogspot.com/ Johan Ferdian Juno Rizkinanda

    I will love this site … With many tutorials of web programming I needs …