February 7, 2024 5:01 am

How to Upload Image using jQuery with progress in PHP

We received many requests from our readers to write some tutorial on upload image with jQuery and show progress bar so here it is, in this tutorial we are using ajax form library to upload image and show a progress in percentage (%) after complete upload show that image on page. Image will be saved on server for that we used PHP coding.

How to Upload Image using jQuery with progress in PHP

index.php

This file Contains html form to upload image

<form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<table width="500" border="0">
  <tr>
    <td>File : </td>
    <td><input name="ImageFile" type="file" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit"  id="SubmitButton" value="Upload" /></td>
  </tr>
</table>
</form>
<div id="progressbox"><div id="progressbar"></div ><div id="statustxt">0%</div ></div>
<div id="output"></div>

jQuery libraries required to process:

<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

Main jQuery code for upload file and progress bar:

<script>
        $(document).ready(function() {
        //elements
        var progressbox     = $('#progressbox');
        var progressbar     = $('#progressbar');
        var statustxt       = $('#statustxt');
        var submitbutton    = $("#SubmitButton");
        var myform          = $("#UploadForm");
        var output          = $("#output");
        var completed       = '0%';

                $(myform).ajaxForm({
                    beforeSend: function() { //brfore sending form
                        submitbutton.attr('disabled', ''); // disable upload button
                        statustxt.empty();
                        progressbox.slideDown(); //show progressbar
                        progressbar.width(completed); //initial value 0% of progressbar
                        statustxt.html(completed); //set status text
                        statustxt.css('color','#000'); //initial color of status text
                    },
                    uploadProgress: function(event, position, total, percentComplete) { //on progress
                        progressbar.width(percentComplete + '%') //update progressbar percent complete
                        statustxt.html(percentComplete + '%'); //update status text
                        if(percentComplete>50)
                            {
                                statustxt.css('color','#fff'); //change status text to white after 50%
                            }
                        },
                    complete: function(response) { // on complete
                        output.html(response.responseText); //update element with received data
                        myform.resetForm();  // reset form
                        submitbutton.removeAttr('disabled'); //enable submit button
                        progressbox.slideUp(); // hide progressbar
                    }
            });
        });

</script>

Styling Progress bar

Used CSS for styling of progress bar.

#progressbox {
border: 1px solid #0099CC;
padding: 1px; 
position:relative;
width:400px;
border-radius: 3px;
margin: 10px;
display:none;
text-align:left;
}
#progressbar {
height:20px;
border-radius: 3px;
background-color: #003333;
width:1%;
}
#statustxt {
top:3px;
left:50%;
position:absolute;
display:inline-block;
color: #000000;
}

processupload.php

Contains back end server side script to handle image and move to uploads directory after adding random number in file name.

if(isset($_POST))
{
    $Destination = 'uploads';
    if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
    {
        die('Something went wrong with Upload!');
    }

    $RandomNum   = rand(0, 9999999999);

    $ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
    $ImageType      = $_FILES['ImageFile']['type']; //"image/png", image/jpeg etc.

    $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
    $ImageExt = str_replace('.','',$ImageExt);

    $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);

    //Create new image name (with random number added).
    $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;

    move_uploaded_file($_FILES['ImageFile']['tmp_name'], "$Destination/$NewImageName");
    echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
    echo '<tr>';
    echo '<td align="center"><img src="uploads/'.$NewImageName.'"></td>';
    echo '</tr>';
    echo '</table>';
}

$Destination = ‘uploads’ is destination folder and after changing we used move_uploaded_file function to move file from temporary location to uploads directory and after that show this image on page.

Upload form all together

This is the complete file code with jquery and css.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>How to Upload Image using jQuery with progress in PHP | PGPGang.com</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">
      img {border-width: 0}
      * {font-family:'Lucida Grande', sans-serif;}
</style>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

<script>
    $(document).ready(function() {
    //elements
    var progressbox     = $('#progressbox');
    var progressbar     = $('#progressbar');
    var statustxt       = $('#statustxt');
    var submitbutton    = $("#SubmitButton");
    var myform          = $("#UploadForm");
    var output          = $("#output");
    var completed       = '0%';

    $(myform).ajaxForm({
        beforeSend: function() { //brfore sending form
        submitbutton.attr('disabled', ''); // disable upload button
        statustxt.empty();
        progressbox.slideDown(); //show progressbar
        progressbar.width(completed); //initial value 0% of progressbar
        statustxt.html(completed); //set status text
        statustxt.css('color','#000'); //initial color of status text
        },
        uploadProgress: function(event, position, total, percentComplete) { //on progress
        progressbar.width(percentComplete + '%') //update progressbar percent complete
        statustxt.html(percentComplete + '%'); //update status text
        if(percentComplete>50)
        {
            statustxt.css('color','#fff'); //change status text to white after 50%
        }
    },
    complete: function(response) { // on complete
    output.html(response.responseText); //update element with received data
    myform.resetForm();  // reset form
    submitbutton.removeAttr('disabled'); //enable submit button
    progressbox.slideUp(); // hide progressbar
}
});
});
</script>
<style>
    #progressbox {
    border: 1px solid #0099CC;
    padding: 1px; 
    position:relative;
    width:400px;
    border-radius: 3px;
    margin: 10px;
    display:none;
    text-align:left;
    }
    #progressbar {
    height:20px;
    border-radius: 3px;
    background-color: #003333;
    width:1%;
    }
    #statustxt {
    top:3px;
    left:50%;
    position:absolute;
    display:inline-block;
    color: #000000;
    }
</style>
</head>
<body>
<form action="processupload.php" method="post" enctype="multipart/form-data" id="UploadForm">
    <table width="500" border="0">
        <tr>
            <td>File : </td>
            <td><input name="ImageFile" type="file" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit"  id="SubmitButton" value="Upload" /></td>
        </tr>
    </table>
</form>
<div id="progressbox">
    <div id="progressbar"></div >
    <div id="statustxt">0%</div >
</div>
<div id="output"></div>
</body>
</html>

Feedback

If you have any issue in its configuration or want to suggest some thing please feel free to comment. For your ease we make its demo and script to download.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

14 responses to “How to Upload Image using jQuery with progress in PHP”

  1. bob says:

    Awesome tutorial ! But to rename image better with time function like

    $RandomNum = time();

  2. siddhu says:

    enjoying the code ….super sir

  3. kobi says:

    i can’t download sir how can i download sir pls?

  4. imran says:

    awesome sir…

  5. Brubru says:

    This code is just what I needed, short, efficient and understandable! Thank you sir

  6. Marcello Patto says:

    Hi dude, how do I uptade my database with those file names?
    Check this out:

    $(document).ready(function()
    {
    var settings = {
    url: “upload.php?id_cliente=””, (<— Added this code! –)
    method: "POST",

    AND

    move_uploaded_file($_FILES[“myfile”][“tmp_name”],$output_dir. $NewImageName);
    $sql = “UPDATE tb_cliente SET docs = ” . $NewImageName . ” WHERE id_cliente = ” . $_POST[‘id_cliente’]; (<— Added this code! –)

    But with no sucess… can you please help me with that?
    Thanks!

  7. Sunny says:

    Hi there!.. this code works perfect.. but how am i suppose to get two different output if i am using the same code at two different places in the same page..

  8. priyadarshini says:

    Hi,

    The code is very useful and easy to understand but only one thing am not able to find is adding cancel button when upload is in progress and when clicked the progress process have to be aborted immediately. can you please help me with this.

  9. Ramesh says:

    how can I put browse button to under displayed images list?

  10. Kazi Nayem says:

    sorry, this gives following error. give me a solution to resolve it please…………………..

    Warning: move_uploaded_file(uploads/5-3570198873.jpg): failed to open stream: Permission denied in /var/www/upload-image-progress-with-jquery/processupload.php on line 24

    Warning: move_uploaded_file(): Unable to move ‘/tmp/phpnKFODb’ to ‘uploads/5-3570198873.jpg’ in /var/www/upload-image-progress-with-jquery/processupload.php on line 24

  11. john stokes says:

    Code works very Well. Excellent Sir.
    Prefer to add a date or consecutive number index derived from a database but that is icing on the cake.
    I would dearly love to be able to preprocess files to compress larger images down to a small sixe before saving in the server directory.

  12. Collins Tagoe says:

    thanks you God bless you..please i want you to help me create a comment box with a reply section..

Leave a Reply

Your email address will not be published. Required fields are marked *