This script works similar to previous post Ajax Image Upload and Resize with jQuery and PHP, but it shows a jQuery progressbar as it uploads file, and then resizes image file using PHP. Please Note: Progressbar only works with modern XMLHttpRequest Level 2 supported browsers.
Style
Our basic style file for the page (style.css).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | body { margin: 0px; padding: 0px; width: 100%; font-family: Arial; color:#666666; } #Wrapper { width: 70%; margin: 50px auto 0px; background: #EEEEEE; padding: 20px; border: 1px solid #E6E6E6; } #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; } |
Index File (index.php)
Upload form page. Image file is uploaded and sent to processupload.php for processing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajax Upload and Resize with jQuery and PHP</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></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> <link href="style/style.css" rel="stylesheet" type="text/css" /> </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>Your Name : </td> <td><input name="username" type="text" id="username" value="Jack Sparrow" /></td> </tr> <tr> <td>Location</td> <td><input name="userlocation" type="text" id="userlocation" value="Troubadour" /></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> |
processupload.php
Uploaded Image files are sent here for processing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | <noscript> <div align="center"><a href="index.php">Go Back To Upload Form</a></div><!-- If javascript is disabled --> </noscript> <?php <?php //ini_set('display_errors', 1); //error_reporting(E_ALL); if(isset($_POST)) { //Some Settings $ThumbSquareSize = 200; //Thumbnail will be 200x200 $BigImageMaxSize = 500; //Image Maximum height or width $ThumbPrefix = "thumb_"; //Normal thumb Prefix $DestinationDirectory = '/home/websites/uploads/'; //Upload Directory ends with / (slash) $Quality = 90; // check $_FILES['ImageFile'] array is not empty // "is_uploaded_file" Tells whether the file was uploaded via HTTP POST if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name'])) { die('Something went wrong with Upload!'); // output error when above checks fail. } // Random number for both file, will be added after image name $RandomNumber = rand(0, 9999999999); // Elements (values) of $_FILES['ImageFile'] array //let's access these values by using their index position $ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name'])); $ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size $TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder $ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc. //Let's use $ImageType variable to check wheather uploaded file is supported. //We use PHP SWITCH statement to check valid image format, PHP SWITCH is similar to IF/ELSE statements //suitable if we want to compare the a variable with many different values switch(strtolower($ImageType)) { case 'image/png': $CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']); break; case 'image/gif': $CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']); break; case 'image/jpeg': case 'image/pjpeg': $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']); break; default: die('Unsupported File!'); //output error and exit } //PHP getimagesize() function returns height-width from image file stored in PHP tmp folder. //Let's get first two values from image, width and height. list assign values to $CurWidth,$CurHeight list($CurWidth,$CurHeight)=getimagesize($TempSrc); //Get file extension from Image name, this will be re-added after random name $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); //remove extension from filename $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); //Construct a new image name (with random number added) for our new image. $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt; //set the Destination Image $thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name $DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image //Resize image to our Specified Size by calling resizeImage function. if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType)) { //Create a square Thumbnail right after, this time we are using cropImage() function if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType)) { echo 'Error Creating thumbnail'; } /* At this point we have succesfully resized and created thumbnail image We can render image to user's browser or store information in the database For demo, we are going to output results on browser. */ //Get New Image Size list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName); echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">'; echo '<tr>'; echo '<td align="center"><img src="uploads/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" height="'.$ThumbSquareSize.'" width="'.$ThumbSquareSize.'"></td>'; echo '</tr><tr>'; echo '<td align="center"><img src="uploads/'.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></td>'; echo '</tr>'; echo '</table>'; /* // Insert info into database table! mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath) VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')"); */ }else{ die('Resize Error'); //output error } } // This function will proportionally resize image function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType) { //Check Image size is not 0 if($CurWidth <= 0 || $CurHeight <= 0) { return false; } //Construct a proportional size of new image $ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight); $NewWidth = ceil($ImageScale*$CurWidth); $NewHeight = ceil($ImageScale*$CurHeight); if($CurWidth < $NewWidth || $CurHeight < $NewHeight) { $NewWidth = $CurWidth; $NewHeight = $CurHeight; } $NewCanves = imagecreatetruecolor($NewWidth, $NewHeight); // Resize Image if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight)) { switch(strtolower($ImageType)) { case 'image/png': imagepng($NewCanves,$DestFolder); break; case 'image/gif': imagegif($NewCanves,$DestFolder); break; case 'image/jpeg': case 'image/pjpeg': imagejpeg($NewCanves,$DestFolder,$Quality); break; default: return false; } //Destroy image, frees up memory if(is_resource($NewCanves)) {imagedestroy($NewCanves);} return true; } } //This function corps image to create exact square images, no matter what its original size! function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType) { //Check Image size is not 0 if($CurWidth <= 0 || $CurHeight <= 0) { return false; } //abeautifulsite.net has excellent article about "Cropping an Image to Make Square" //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/ if($CurWidth>$CurHeight) { $y_offset = 0; $x_offset = ($CurWidth - $CurHeight) / 2; $square_size = $CurWidth - ($x_offset * 2); }else{ $x_offset = 0; $y_offset = ($CurHeight - $CurWidth) / 2; $square_size = $CurHeight - ($y_offset * 2); } $NewCanves = imagecreatetruecolor($iSize, $iSize); if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)) { switch(strtolower($ImageType)) { case 'image/png': imagepng($NewCanves,$DestFolder); break; case 'image/gif': imagegif($NewCanves,$DestFolder); break; case 'image/jpeg': case 'image/pjpeg': imagejpeg($NewCanves,$DestFolder,$Quality); break; default: return false; } //Destroy image, frees up memory if(is_resource($NewCanves)) {imagedestroy($NewCanves);} return true; } } |

Hello, thank you for the amazing script, I like it very much. I have tried to upload multiple files. I have changed the input into . But the php file works only with one image, how does it work with multiple images? Best regards, Marc
Hi,
I am getting the following erro can you please advise
2
3
4
5
6
php.java.servlet.fastcgi.FastCGIServlet.handle(FastCGIServlet.java:499)
php.java.servlet.fastcgi.FastCGIServlet.doPost(FastCGIServlet.java:509)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
2
3
4
5
6
7
8
php.java.servlet.fastcgi.FastCGIServlet.parseBody(FastCGIServlet.java:409)
php.java.servlet.fastcgi.FastCGIServlet.execute(FastCGIServlet.java:433)
php.java.servlet.fastcgi.FastCGIServlet.handle(FastCGIServlet.java:481)
php.java.servlet.fastcgi.FastCGIServlet.doPost(FastCGIServlet.java:509)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
Check GD is properly installed http://j.mp/TrpzJs
Melvin, you need to check that GD is installed on your server…..And version 1.8 or above but im sure it will be if it is installed correctly.
Thank you for this form.
Like others, I have a problem with the copy of the picture, with this famous message : Unable to open ‘images/’… for writing.
I read the code, and I was unable to find the part where you copy the image.
Can you light me ?
Thanks !
I managed to get this 100% working, but then I ran into problems uploading images from an iPhone. PHP would give memory errors when trying to upload, but only when sending photos from an iPhone, not from a computer. I thought maybe the photo was too large (3-4 MB), but even sending a small screenshot (less than 1 MB) same problem. Sending photos from a regular computer works fine. Then I ran into a caching problem where uploading photos would just zip the progress bar to 100% instantly and then display the first file I uploaded instantly. Again, only on the iphone – maybe because the files are all named the same (ie – photo.jpg) coming from iphone. It’s possible I need to modify the PHP script to add on the random number to the filename earlier in the script. I spent the entire day yesterday trying to get it working, and it’s a very cool piece of code, just has a couple major bugs. If/when I find a solution, I will post it here. Thanks Saaraan for posting this.
This works great from a desktop/laptop PC using Chrome, however there is a problem using mobile Safari (iPhone) to upload images. Image uploading via iphone only works the very first time. Subsequent uploads fail and the previously uploaded image is shown. It’s like it’s somehow caching the first upload. I’ve tried 3 differentiphones now and all exhibit the same behaviour. First upload works great, all uploads from then on fail. Closing the window or quitting Safari and reloading does not fix this, neither does a hard reset on the phone. I don’t know where to even start looking to solve a bug like this..
Scott, I have the *exact* same issue.
I’ve found that if you set the iPhone to private browsing mode, then kill all tabs, then reload the page — the first upload works again, but all subsequent uploads fail (until you kill all private windows again).
So far, it appears that the uploadProgress (or complete, or anything) function is not being called at all on mobile Safari (it works fine on desktop safari). beforeSend() seems to be the last thing executed (happily too, I’ll add). I was looking into ways to debug this, but you can only access debugging tools (like the JavaScript console) by connecting the iPhone to your Mac computer with a cable, and setting it up to interface with Desktop Safari 6 for Mac. I have Windows (safari 6 dropped windows support), and the Macs I have aren’t running the latest Mac OS X that Safari 6 requires. So I’m out of luck. If anyone has the same issue and is equipped to debug it, please let me and Scott know what’s up.
Otherwise, I might just shit all over jquery.form.js’s source code with a ton of alerts to hack this down the ol’ fashion way. If I figure anything out, I’ll post back
//Chase.
Hey.
I found the issue.
Google “iPhone Post Caching”.
Will be fixed in iOS 6.1.
Workaround: add a timestamp parameter to the querystring to kill the caching.
//Chase.
hello,
If I insert the imaged uploaded to mysql database successfull.
How can it redirect to that image automatically?
Thank you
Progress bar works fine, but after complete it returns me the “404 not found” error.
Thanks!
Salam
Thanks.This code is nice,simple and useful.
Best Regard.
Thanks a lot for this. Really made by project quicker to complete. Just a little typo error in your commenting on line 20 of index.php (beforeSend: function() { //brfore sending form). But sincerely, it’s a great piece of work to use. Thanks.
Warning: imagejpeg(/home/ajax-image-upload-progressbar/uploads/6-621637111.jpg): failed to open stream: No such file or directory in C:xampphtdocsimagesprocessupload.php on line 144
Warning: imagejpeg(/home/ajax-image-upload-progressbar/uploads/thumb_6-621637111.jpg): failed to open stream: No such file or directory in C:xampphtdocsimagesprocessupload.php on line 191
Warning: getimagesize(/home/ajax-image-upload-progressbar/uploads/6-621637111.jpg): failed to open stream: No such file or directory in C:xampphtdocsimagesprocessupload.php on line 84
i facing problem with this error in both the codings and working in the local.
Please do reply soon
Thanks very much. This really helped me a lot. I’ve been searching very hard for how to upload images via ajax although I can send text entered in forms via ajax but with uploading images or any other file, it was very difficult. Thanks again, dude.
I tried and it worked so fine!…Thanks a lot!
Hey;
thumb image working but not my request type. normal image fine but thumb image looking middle part of image means buttom and top cropped this looks bad .how can i fix that.
I saaraan i have tried my script today but i have a problem: it says to me “The requested URL /scripts/upload/upload.php was not found on this server.” the problem is i dont see it in my zip file…what’s wrong with it?
thanks
Alessandro
you need to change this line “action=”upload.php”" with “action=”processupload.php”" in index.php.
Hello,
please can I ask for following advice? If I want after uploading be redirected to form action, how to do it?
I mean, for example in form is “action=’/test/’”. I dont want see the output of /test/ on original page, but I want be redirected to /test/, as common form does.
Please can you help me?
If I understood you correctly, you don’t need any jQuery code, you can achieve that with normal form.
What I would like to use is progress bar – this progress bar is nice and work as I need. So if would be possible to see progress bar while files are uploading and then go to form action, it would be nice …
Hi guys thanks for your answers, i was able to fix the script and i could also copy the cropped images into two different folders customizing it a little bit. It a very clear script, compliments. Just one suggest i have for you…it would be nice, if it loads the image just when i release the button on input file text (like facebook style) I see my image loaded and then just in a second moment, i can press the submit button and send the form to db…in this way it’s less useful have the preload, because after have submitted a form i don’t need to see my image loaded, or i could do also refreshing my page without ajax…
i try in case to customize it more, maybe i could do two loops on ajax file, i have no idea yet…thanks a lot anyways!…
The progressbar is not working in ie 8.
Plz help.
Most of the features in HTML5 isn’t supported by IE8.
But i want it in ie 8 bcoz my client required this functionality in ie 8 i have another uploader which perfectly run in other browsers but at the end ie 8 support is important.
this do not work in IE9
Any suggestion?
Tks
The script is very nice but does not work on IE 9.
Someone tried the solution?
Thanks
Can i use form validation ? Such as check empty field before upload executed?
yes sure you can.
How Can I do that ? Can you help me?
This is my code, it works but it makes the progress bar doesn’t showed.
$(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%’;
var numbers = /^[0-9]+$/;
if(document.getElementById(‘name’).value == “”){
return false;
} else if(!document.getElementById(‘price’).value.match(numbers)){
return false;
} else if(document.getElementById(‘category_id’).value 50)
{
statustxt.css(‘color’,'#fff’); //change status text to white after 50%
}
},
complete: function(response) { // on complete
myform.resetForm(); // reset form
submitbutton.removeAttr(‘disabled’); //enable submit button
progressbox.hide(); // hide progressbar
window.location = “stores/manage”;
}
});
});
Warning: imagejpeg() [function.imagejpeg]: Unable to open ‘/imgUpload/uploads/desert-8587226350.jpg’ for writing: No such file or directory
i get this error
Make sure about permissions of the directory is correct..
Hi Saaraan,
I am done this for to upload video but i am getting error while uploading error is internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, webmaster@halla.palride.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Can you plz help me with this problem?