Top

Follow me and receive all the latest free scripts:

By Email:

Categories
Most Popular Posts

Ajax upload image using jQuery

Ajax upload image using jQuery

Published October 05, 2014 by , category jQuery

Ajaxjqueryupload imagejquery form plugin

How to upload an image using Ajax and jQuery, without refreshing page

Introduction

If you are looking for a tutorial to upload an image, without refreshing page and using jQuery, you are at the right place.

To proceed, I use jQuery of course, and a jQuery plugin called jQuery Form Plugin.

You will also notice that I have added and used 2 functions:

  1. crop_img: to crop an image, I use it to create the image thumbnail
  2. convert_str: to convert a string in a format like string-string-string.jpg

I use convert_str to rename the image I want to upload. Often images have a weird name including "_", "spaces", ":" etc. I just want to get a better name and replace all these characters by "-".

Feel free of course to use your own system, for example if you want a member to upload a profile image, you may want to name the image "profile-photo" + the member ID.

What is jQuery Form Plugin

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted.

For more information, go there https://github.com/malsup/form

Files architecture

index.php
db.class.php

ajax

tuto-upload-image.php

jquery

jquery-1.10.1.min.js
jquery.form.js

upload

There is an "upload" folder. It's where images and thumbnails will be stored

Live demo

For safety reasons and to prevent misuse, datas are not inserted in the database, and images are not stored.

Upload your image Max: 256 Kb; jpg, jpeg, png & gif

Database structure sample

id is the "id" (database row number) of the image stored. Notice that I store the date and time when the image has been uploaded (not required of course), the original image and it's thumbnail.

CREATE TABLE IF NOT EXISTS `tc_tuto_upload_image` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `date_ins` date NOT NULL DEFAULT '0000-00-00',
  `hour_ins` time NOT NULL DEFAULT '00:00:00',
  `img_thumb` varchar(255) NOT NULL,
  `img_original` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 ;

HTML code

Include this code in your index.php page (or any page you want the script appears), between <body></body>.

<div id="result"></div>
			
<form method="post" enctype="multipart/form-data" id="MyImageUploadForm" action="ajax/tuto-upload-image.php">
	<p><input name="image" id="image" type="file" /></p>
</form>

jQuery code

Include this code in your index.php page, just before the </body>, or in your footer.php page if you have one...

There is a design/loader.gif icon, it appears in the div#result node, waiting for the image to be uploaded...You can get an icon here http://www.ajaxload.info

<script type="text/javascript" src="jquery/jquery-1.10.1.min.js"></script>
<script src="jquery/jquery.form.js"></script>
<script type="text/javascript">
	$(function() {
		$('#image').bind('change', function() {
			$("#result").html('<img src="design/loader.gif" alt="" />'); // a loader icon: waiting for the image
			$('#MyImageUploadForm').ajaxForm({
				target: '#result'
			}).submit();
		});
	});
</script>

PHP code

It's the ajax/tuto-upload-image.php file, including the crop_img function and the convert_str function. Functions may be placed in another file, a functions.php file if you have one. Don't forget to call this file at the beginning of the code of course :) with an include('../functions.php');

Lines are commented. You can easily adapt the script, remove what you don't need. For example, you may not need the thumbnail! So don't copy the image (remove line 21, 22), remove the crop_img function and lines 25 to 31, and remove the img_thumb field in your table.

<?php
include('../db.class.php');
$bdd = new db();

$acceptedExtension = Array('image/jpeg', 'image/jpg', 'image/pjpg', 'image/pjpeg', 'image/png', 'image/gif'); // add here allowed extensions
$maxSize = 5000000; //image size max = 5Mb
$destFolder = 'upload/';

$imgType = $_FILES["image"]["type"];
$imgSize = $_FILES["image"]["size"];
$imgName = $_FILES["image"]["name"];
$imgTmpName = $_FILES["image"]["tmp_name"];

if (in_array($imgType, $acceptedExtension) && $imgSize <= $maxSize && $imgSize != "") { // we test the validity of the image

	$newOriginalImageName = convert_str($imgName); // we give our original photo a new name (we convert the string with the function convert_str below)
	$newThumbImageName = 'small-'.convert_str($imgName); // same we give a name the thumbnail (the same name than the original but starting with "small-")

	if(move_uploaded_file($imgTmpName,"../".$destFolder.$newOriginalImageName)) { // test if the original image is moved on the server
		
		copy("../".$destFolder.$newOriginalImageName, "../".$destFolder.$newThumbImageName); // we copy the origininal image and rename it (it will be our thumbnail)
		chmod ("../".$destFolder.$newThumbImageName, 0777); // we change the chmod so we can crop
				
		// we crop the photo
		list($width, $height, $type, $attr) = getimagesize("../".$destFolder.$newOriginalImageName); // we take the image height and width
		// the crop function is below
		if ($width>$height) { // if the image is landscape style
			crop_img ("../".$destFolder.$newThumbImageName, 160, 120); // we crop and resize 160x120px
		} else { // if the image is portrait style
			crop_img ("../".$destFolder.$newThumbImageName, 120, 160);// we crop and resize 120x160px
		}
		
		// we instert into database; the thumbnail path and the original path
		$upload = $bdd->execute('INSERT INTO tc_tuto_upload_image (date_ins, hour_ins, img_thumb, img_original) VALUES (NOW(), NOW(), "'.$newThumbImageName.'", "'.$newOriginalImageName.'")');
		
		echo '<p><img src="'.$destFolder.$newThumbImageName.'" alt="" class="img-thumbnail" /></p>'; // we send back the thumbnail
	}

} else {
	echo 'Error with your image (wrong format or size)!';
}

// crop function (feel free to adapt)
function crop_img ($image, $thumb_width, $thumb_height) {
	$filename = $image;
	$image = imagecreatefromstring(file_get_contents("$image"));

	$width = imagesx($image);
	$height = imagesy($image);

	$original_aspect = $width / $height;
	$thumb_aspect = $thumb_width / $thumb_height;

	if ( $original_aspect >= $thumb_aspect ) {
	   // If image is wider than thumbnail (in aspect ratio sense)
	   $new_height = $thumb_height;
	   $new_width = $width / ($height / $thumb_height);
	} else {
	   // If the thumbnail is wider than the image
	   $new_width = $thumb_width;
	   $new_height = $height / ($width / $thumb_width);
	}

	$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

	// Resize and crop
	imagecopyresampled($thumb,
		$image,
		0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
		0 - ($new_height - $thumb_height) / 2, // Center the image vertically
		0, 0,
		$new_width, $new_height,
		$width, $height);
	
	return imagejpeg($thumb, $filename, 80);
}

// convert string function (feel free to adapt)
function convert_str($str) {	
	$str = str_replace(
		array(' : ',': ',' !',' ?','!','?','"','\'',', ','(',')',' / ','/',' « ',' » ','  ',' ','&','_'),
		array(  '-', '-',  '',  '', '', '', '', '-', '-', '', '',  '-','-',  '-',  '-', '-','-','-','-'),
		$str
	);

	$str = str_replace(
		array('    ','   ','  ',' ','----','---','--'),
		array(    '',   '',  '', '',   '-',  '-', '-'),
		$str
	);
	
	$str = strtolower($str);
	
	return $str;
}
?>

Database connection

Page db.class.php. More information about the database connection I use here.

Conclution

Have fun with these few lines of code, hope it will help.

In my next tutorial I will talk about upload multiple images using PHP and jQuery.

About Simon Laroche
Simon Laroche on Google+
Simon Laroche on Twitter
Simon Laroche on Facebook
Simon Laroche on Pinterest
Simon Laroche on LinkedIn
: I am a Coder, Designer, Webmaster and Expert SEO Consulting, I'm also a wise traveller and an avid amateur photographer. I created the website TipoCode and many others such as Landolia: a World of Photos...

If you need help about this script, please leave a comment below. I reply as much as I can depending of my time, you may also get help from others.
I also offer a paid support, if you are in the need to adapt or create a script...

Leave a comment

Comments (4 comments)

Angel Posted on August 25, 2016
nice :)
Ricardo Posted on April 30, 2015
How can i set a max height to crop?
Simon Laroche
Simon Laroche Posted on October 10, 2014
@Ali Kazmi,
About the Entity–relationship model, I don't think you need one as there is only one table.
Or I didn't get what you need... :)
Ali Kazmi Posted on October 10, 2014
What is the coding of ER diagram on MYSQL ??