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.
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> </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> </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.
Tutorial Categories:
Awesome tutorial ! But to rename image better with time function like
$RandomNum = time();
enjoying the code ….super sir
i can’t download sir how can i download sir pls?
awesome sir…
This code is just what I needed, short, efficient and understandable! Thank you sir
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!
What is your error exactly?
Nothing happens at all! The upload.php dont get the “?id_cliente…” code from the url.Should be a easylly way to do it…
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..
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.
how can I put browse button to under displayed images list?
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
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.
thanks you God bless you..please i want you to help me create a comment box with a reply section..