Ajax Multiple Image Upload-Resize with jQuery and PHP

If you are looking for multiple image uploader that doesn’t require flash plugin, here’s script that does it for you, it will nicely upload multiple image files and resize them using jQuery and PHP. User can easily add as many files before uploading and a nice progress bar lets you see the progress of the upload, but please note: progress bar requires modern browsers to function. 

Thanks to Marc Heiduk for rewriting and sending me this modified version of Ajax Image Upload and Resize script with Progressbar. It was working nicely, processing multiple uploaded files, but I needed to modify it a little. This is a very nice script, but still you can run into errors while uploading big size files if settings aren’t set right in PHP.ini file, so make sure “upload_max_filesize“, “post_max_size” and “memory_limit” in PHP.ini file are adequate for big file uploading.

This script is modified version of previous single file uploader scripts, so you may also find other posts interesting Ajax Image Upload and Resize with jQuery and PHP and Ajax Image Upload with Progressbar with jQuery and PHP.

Upload Form

Upload form is presented to user with option to add/remove file input fields, you can limit how many input fields should be addable by users. Upload form is nicely styled with CSS file, and includes jQuery Ajax to upload files. Main thing to notice here is file input boxes, with attribute names “file[]“, this name creates an array of files which can be accessed using $_POST or $_FILES in upload.php or other receiver script, where these data will be posted.

HTML
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Multiple Image Upload</title>
<script src="//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 type="text/javascript">
$(document).ready(function() {
//elements
var progressbox 		= $('#progressbox'); //progress bar wrapper
var progressbar 		= $('#progressbar'); //progress bar element
var statustxt 			= $('#statustxt'); //status text element
var submitbutton 		= $("#SubmitButton"); //submit button
var myform 				= $("#UploadForm"); //upload form
var output 				= $("#output"); //ajax result output element
var completed 			= '0%'; //initial progressbar value
var FileInputsHolder 	= $('#AddFileInputBox'); //Element where additional file inputs are appended
var MaxFileInputs		= 3; //Number of file input fields allowed to add
// adding and removing file input box
var i = $("#AddFileInputBox div").size() + 1;
$("#AddMoreFileBox").click(function () {
		event.returnValue = false;
		if(i < MaxFileInputs)
		{
			$('<span><input type="file" id="fileInputBox" size="20" name="file[]" class="addedInput" value=""/><a href="#" class="removeclass small2"><img src="images/close_icon.gif" border="0" /></a></span>').appendTo(FileInputsHolder);
			i++;
		}
		return false;
});
$("body").on("click",".removeclass", function(e){
		event.returnValue = false;
		if( i > 1 ) {
				$(this).parents('span').remove();i--;
		}	
}); 
$("#ShowForm").click(function () {
  $("#uploaderform").slideToggle(); //Slide Toggle upload form on click
});
$(myform).ajaxForm({
	beforeSend: function() { //brfore sending form
		submitbutton.attr('disabled', ''); // disable upload button
		statustxt.empty();
		progressbox.show(); //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%
			}else{
				statustxt.css('color','#000');
			}
		},
	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.hide(); // hide progressbar
		$("#uploaderform").slideUp(); // hide form after upload
	}
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="uploaderform">
<form action="upload.php" method="post" enctype="multipart/form-data" name="UploadForm" id="UploadForm">
<h1>Multi image file upload with PHP and jQuery</h1>
Each recommended image file size must be less than 1MB!
    <label>Files
    <span class="small"><a href="#" id="AddMoreFileBox">Add More Files</a></span>
    </label>
<div id="AddFileInputBox"><input id="fileInputBox" style="margin-bottom: 5px;" type="file"  name="file[]"/></div>
<div class="sep_s"></div>
    <label>Name
    <span class="small">Enter your name</span>
    </label>
<div><input name="username" type="text" id="username" value="Jack Sparrow" /></div>
    <label>Location
    <span class="small">Your Location</span>
    </label>
<div><input name="userlocation" type="text" id="userlocation" value="Troubadour" /></div>
    <button type="submit" class="button" id="SubmitButton">Upload</button>
<div id="progressbox">
<div id="progressbar"></div >
<div id="statustxt">0%</div ></div>
</form>
</div>
<div id="uploadResults">
<div align="center" style="margin:20px;"><a href="#" id="ShowForm">Toggle Form</a></div>
<div id="output"></div>
</div>
</body>
</html>

Upload Process

Upload.php script processes the uploaded image files. Once file is uploaded PHP creates temporary copy of the uploaded files in the PHP temp folder, the variables posted from upload form with fields name file[] and other variables are retrieved here as an array using $_FILES, and then it simply copies temporary files from PHP tmp folder into destination folder.

PHP
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214

<noscript>
<div align="center"><a href="index.php">Go Back To Upload Form</a></div>
<!-- If javascript is disabled -->
</noscript>
<?php
//If you face any errors, increase values of "post_max_size", "upload_max_filesize" and "memory_limit" as required in php.ini

 //Some Settings
$ThumbSquareSize 		= 200; //Thumbnail will be 200x200
$BigImageMaxSize 		= 500; //Image Maximum height or width
$ThumbPrefix			= "thumb_"; //Normal thumb Prefix
$DestinationDirectory	= '/websites/fbphoto/uploads/'; //Upload Directory ends with / (slash)
$Quality 				= 90;

//ini_set('memory_limit', '-1'); // maximum memory!

foreach($_FILES as $file)
{
// some information about image we need later.
$ImageName 		= $file['name'];
$ImageSize 		= $file['size'];
$TempSrc	 	= $file['tmp_name'];
$ImageType	 	= $file['type'];


if (is_array($ImageName))
{
	$c = count($ImageName);

	echo  '

<ul>';
	for ($i=0; $i < $c; $i++)
	{
		$processImage			= true;
		$RandomNumber			= rand(0, 9999999999);  // We need same random name for both files.

		if(!isset($ImageName[$i]) || !is_uploaded_file($TempSrc[$i]))
		{
			echo '

<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>, may be file too big!</div>
'; //output error
		}
		else
		{
			//Validate file + create image from uploaded file.
			switch(strtolower($ImageType[$i]))
			{
				case 'image/png':
					$CreatedImage = imagecreatefrompng($TempSrc[$i]);
					break;
				case 'image/gif':
					$CreatedImage = imagecreatefromgif($TempSrc[$i]);
					break;
				case 'image/jpeg':
				case 'image/pjpeg':
					$CreatedImage = imagecreatefromjpeg($TempSrc[$i]);
					break;
				default:
					$processImage = false; //image format is not supported!
			}
			//get Image Size
			list($CurWidth,$CurHeight)=getimagesize($TempSrc[$i]);
			//Get file extension from Image name, this will be re-added after random name
			$ImageExt = substr($ImageName[$i], strrpos($ImageName[$i], '.'));
			$ImageExt = str_replace('.','',$ImageExt);
			//Construct a new image name (with random number added) for our new image.
			$NewImageName = $RandomNumber.'.'.$ImageExt;
			//Set the Destination Image path with Random Name
			$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($processImage && resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
			{
				//Create a square Thumbnail right after, this time we are using cropImage() function
				if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType[$i]))
					{
						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 '
<li>
<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>
</li>
';
					/*
					// Insert info into database table!
					mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
					VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
					*/
			}else{
				echo '
<div class="error">Error occurred while trying to process <strong>'.$ImageName[$i].'</strong>! Please check if file is supported</div>
'; //output error
			}
		}
	}
	echo '</ul>
';
	}
}
// 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;
		}
	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;
		}
	if(is_resource($NewCanves)) {
      imagedestroy($NewCanves);
    }
	return true;
	}
}
?>

Download Demo

  • 39 Comments

    Add Comment
    • Sarokar NGO
      I am not able to finish this multiple.
    • Sangam
      How to add form data and images together in Mysql databases? Thank you in advance.
    • SSngam
      How to add form data and images together in myS
    • Sangam
      How can we add those images and form data together in Mysql database? Can anyone help me please?
    • Lon Sabala
      Interesting article . For my two cents , if someone wants to merge PDF files , my wife saw announcement herehttps://goo.gl/W5uFRb
    • Germano
      Hi, The code is great, could you please show how to insert image urls to a database using object-oriented php function? Please Help.
    • Moin
      Really Doing Grate Code, But one query how to insert this record in database if i have a 2 table product product_image
    • Ian Haney
      Hi I am using this script and works perfect but is there a way so that it does not upload a large version and a thumbnail version of the image, I only want the thumbnail version to show if possible and also after upload, is there a way the page can refresh itself to show the images uploaded please? Thank you in advance Ian
    • Reza
      hi i am not speak english good. pl help me. i want remove and delet the image after upload. code?
    • Eggert
      Hi, I get the downloaded demo working nicely, but when implemented in my website page, I get this error (after some debugging): Object doesn't support property or method ajaxSubmit. on: $('#MyUploadForm').submit(function() { $(this).ajaxSubmit(options); Is it possible because I am also using the: Ajax Image Upload and Resize with jQuery and PHP, which is workin perfectly though? Might there be conflict with the other upload jQuery declaration? Please advice, thx.