Ajax Multiple Image Upload With Resize Using jQuery PHP

Posted by & filed under Ajax, HTML5, JQUERY, MYSQL, PHP.

In previous tutorial I had explained ajax single image upload using jQuery and PHP.

Ajax Image Upload Using jQuery, PHP and MySQL

In this tutorial we are going to see Ajax Multiple Image Upload With Resize Using jQuery PHP and  MySQL. To enable a user let select multiple image using single file input element you need to create a HTML file input element with the following properties.

<input multiple="multiple" type="file" name="images[]" id="images">

Where

multiple=”multiple”  :  this attribute of the input file element, let the user to select multiple images.

name=”images[]” : here naming  the input file element in array format keeps all selected images property in array format. So that you easily handle images upload on the server side.

 

 

Ajax Multiple Image Upload With Resize Using jQuery PHP

Ajax Multiple Image Upload With Resize Using jQuery PHP

Step 1:

Create index.php file with HTML form and file input element with needed attributes to let user to select multiple images. Here is the HMTL file source.

<?php require_once 'config.php';?>
<!DOCTYPE html> 
<html>
<head>
	<title>Ajax Multiple Image Upload With Resize Using jQuery PHP</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="css/style.css" >	
</head>
<body>
	<div class="container">
		<h1 class="page-title" >Ajax Multiple Image Upload With Resize Using jQuery PHP</h1>
		<div class="form-container">
			<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="ajax.php">
				<div class="form-group">
					<p>Please Choose Image: </p>
					<input class='file' multiple="multiple" type="file" class="form-control" name="images[]" id="images" placeholder="Please choose your image">
					<span class="help-block"></span>
				</div>
				<div id="loader" style="display: none;">
					Please wait image uploading to server....
				</div>
				<input type="submit" value="Upload" name="image_upload" id="image_upload" class="btn"/>
			</form>
		</div>
		<div class="clearfix"></div>
		<div id="uploaded_images" class="uploaded-images">
			<div id="error_div">
			</div>
			<div id="success_div">
			</div>
		</div>
	</div>
	<input type="hidden" id='base_path' value="<?php echo BASE_PATH; ?>">
	<script src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/jquery.form.min.js"></script>
    <script src="js/script.js"></script>
</body>
</html>

 

 

Step2:

Now add folloowing two jquery libraries, these two are responsible for ajax multiple image upload.

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

Create script.js where we are going to keep our jQuery scripts.

<script src="js/script.js"></script>

Step 3:

Here is the script.js full jQuery script. This script.js is responsible for following operations

1. Do the validation before HMTL Form is submitted via ajax to the server, and asks to user to select valid images to upload.

2. Once the validations are success, it will post the HMTL Form via Ajax to the server.

3. At end of ajax image upload, it gets the response from the server and shows success or errors based the response from the server.

(function() {
	$('form').ajaxForm({
		beforeSubmit: function() {	
			count = 0;
			val = $.trim( $('#images').val() );
			console.log(val);

			if( val == '' ){
				count= 1;
				$( "#images" ).next('span').html( "Please select your images" );
			}

			if(count == 0){
				for (var i = 0; i < $('#images').get(0).files.length; ++i) {
			    	img = $('#images').get(0).files[i].name;
			    	var extension = img.split('.').pop().toUpperCase();
			    	if(extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
			    		count= count+ 1
			    	}
			    }
				if( count> 0) $( "#images" ).next('span').html( "Please select valid images" );
			}

		    if( count> 0){
		    	return false;
		    } else {
		    	$( "#images" ).next('span').html( "" );
		    }

	    },

		beforeSend:function(){
		   $('#loader').show();
		   $('#image_upload').hide();
		},
	    success: function(msg) {
	    },
		complete: function(xhr) {
			$('#loader').hide();
			$('#image_upload').show();

			$('#images').val('');
			$('#error_div').html('');
			result = xhr.responseText;
			result = $.parseJSON(result);
			base_path = $('#base_path').val();
			$.each(result, function(index, value){
				if( value.success ){
					name = base_path+'images/'+value.success;
					html = '';
					html+= '<image src="'+name+'">';
					$('#uploaded_images #success_div').append( html );
				} else if( value.error ){
					error = value.error
					html = '';
					html+='<p>'+error+'</p>';
					$('#uploaded_images #error_div').append( html );
				}

			});
			$('#error_div').delay(5000).fadeOut('slow');

		}
	}); 

})();

Step4:

Here comes PHP part, once HTML Form is posted using ajax to the server. PHP script get the all image properties (name, size and etc.) in array format. where this array is not proper format to handle, so we  need to restructured it.

function restructure_array(array $images)
{
	$result = array();

	foreach ($images as $key => $value) {
		foreach ($value as $k => $val) {
			for ($i = 0; $i < count($val); $i++) {
				$result[$i][$k] = $val[$i];
			}
		}
	}

	return $result;
}

Following PHP script which generates thumbnail while uploading image to the server. Mostly these script will helpful to generate thumbnail for the user who is going to set profile pic as larger one, where you need to resize that larger image and set it as their profile pic. Here is the script.

function thumbnail($src, $dist, $dis_width = 100 ){

	$img = '';
	$extension = strtolower(strrchr($src, '.'));
	switch($extension)
	{
		case '.jpg':
		case '.jpeg':
			$img = @imagecreatefromjpeg($src);
			break;
		case '.gif':
			$img = @imagecreatefromgif($src);
			break;
		case '.png':
			$img = @imagecreatefrompng($src);
			break;
	}
	$width = imagesx($img);
	$height = imagesy($img);

	$dis_height = $dis_width * ($height / $width);

	$new_image = imagecreatetruecolor($dis_width, $dis_height);
	imagecopyresampled($new_image, $img, 0, 0, 0, 0, $dis_width, $dis_height, $width, $height);

	$imageQuality = 100;

	switch($extension)
	{
		case '.jpg':
		case '.jpeg':
			if (imagetypes() & IMG_JPG) {
				imagejpeg($new_image, $dist, $imageQuality);
			}
			break;

		case '.gif':
			if (imagetypes() & IMG_GIF) {
				imagegif($new_image, $dist);
			}
			break;

		case '.png':
			$scaleQuality = round(($imageQuality/100) * 9);
			$invertScaleQuality = 9 - $scaleQuality;

			if (imagetypes() & IMG_PNG) {
				imagepng($new_image, $dist, $invertScaleQuality);
			}
			break;
	}
	imagedestroy($new_image);
}

Finally here image upload script. Which validates given images, once the validation success it will uploads that image to server or else it sends proper error response to the client side.

$data = array();
if( isset( $_POST['image_upload'] ) && !empty( $_FILES['images'] )){
	//get the structured array
	$images = restructure_array(  $_FILES );
	$allowedExts = array("gif", "jpeg", "jpg", "png");

	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		$ip = $_SERVER['REMOTE_ADDR'];
	}

	foreach ( $images as $key => $value){
		$i = $key+1;
		//create directory if not exists
		if (!file_exists('images')) {
			mkdir('images', 0777, true);
		}
		$image_name = $value['name'];
		//get image extension
		$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
		//assign unique name to image
		$name = $i*time().'.'.$ext;
		//$name = $image_name;
		//image size calcuation in KB
		$image_size = $value["size"] / 1024;
		$image_flag = true;
		//max image size
		$max_size = 512;
		if( in_array($ext, $allowedExts) && $image_size < $max_size ){
			$image_flag = true;
		} else {
			$image_flag = false;
			$data[$i]['error'] = 'Maybe '.$image_name. ' exceeds max '.$max_size.' KB size or incorrect file extension';
		} 

		if( $value["error"] > 0 ){
			$image_flag = false;
			$data[$i]['error'] = '';
			$data[$i]['error'].= '<br/> '.$image_name.' Image contains error - Error Code : '.$value["error"];
		}

		if($image_flag){
			move_uploaded_file($value["tmp_name"], "images/".$name);
			$src = "images/".$name;
			$dist = "images/thumbnail_".$name;
			$data[$i]['success'] = $thumbnail = 'thumbnail_'.$name;
			thumbnail($src, $dist, 200);
			$sql="INSERT INTO images (`id`, `original_image`, `thumbnail_image`, `ip_address`) VALUES (NULL, '$name', '$thumbnail', '$ip');";
			if (!mysqli_query($con,$sql)) {
				die('Error: ' . mysqli_error($con));
			} 

		}
	}
	mysqli_close($con);
	echo json_encode($data);

} else {
	$data[] = 'No Image Selected..';
}

 

 

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni2explore[at]gmail.com

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

Get Instant Script Download Access!