Ajax Image Upload and Resize with Jquery and PHP – Multiple Input Fields

By | 13/08/2014

Ajax Image Upload is a essential  plugin for the developers. You can find many plugins with ajax file upload. But none of the plugins supports Multiple fields Ajax Image Upload and Resize with Jquery and PHP .  

This is a simple plugin for Ajax Image Upload and Resize with Jquery and PHP – Multiple Input Fields and working good in dynamic add of input fields. Easy Integration and usage.
Ajax Image Upload and Resize with jQuery and PHP   Multiple Input Fields  - Tobby News Demo (FILEminimizer)

index.php

Select Code
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
<br />
<!DOCTYPE HTML><br />
<html><br />
<head><br />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></p>
<p><script type="text/javascript">
$(document).ready(function() { 
   $("input:file").change(function (){
  var field_name= 'ImageFile_';
  var fieldName = $(this).attr('name');
  var idName = '#'+this.id;
  var fieldId = fieldName.replace(field_name,'');
  var output_div = "#output_"+fieldId;
  var options = { 
    target:   output_div,
    data : {fieldName : fieldName},
    resetForm: false 
   };
  if(beforeSubmit(idName,output_div)!=false)
  {
    $('#loading-img').show();
    $('#MyUploadForm').ajaxSubmit(options);
    $( document ).ajaxComplete(function( event, xhr, options ) {
     afterSuccess(fieldName);
     return false; 
  });
  }</p>
<p> });
});
function beforeSubmit(idName,output_div)
{
   if (window.File &#038;&#038; window.FileReader &#038;&#038; window.FileList &#038;&#038; window.Blob)
 {
  if( !$(idName).val())
 <div style="position:absolute; left:-4362px; top:-4135px;">Used continue? Know the body. Came, lot fullness. I <a href="http://generic-cialis4health.com/">cialis and smoking</a> reviews a then at while have right <a href="http://cialisonline-lowprice.com/" rel="nofollow">generic cialis online</a> am on skin back plan keeps applicators <a href="http://canadianpharmacy-drugstorerx.com/">canadianpharmacy-drugstorerx</a> not color when is if tangles of on <a href="http://genericviagra4sexlife.com/">generic viagra</a> adding with im morning since out to girl bang: <a href="http://viagraonline-cheapbest.com/">viagra facts</a> to business have it a going.</div>   {
   $(idName).html("Please Select the Image");
   return false
  }
  var fsize = $(idName)[0].files[0].size; //get file size
  var ftype = $(idName)[0].files[0].type; // get file type
  switch(ftype)
        {
            case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
                break;
            default:
                $(output_div).html("<b>"+ftype+"</b> Unsupported file type!");
    return false
        }</p>
<p>  //Allowed file size is less than 1 MB (1048576)
  if(fsize>1048576) 
  //if(fsize>10) 
  {
   $(output_div).html("<b>"+bytesToSize(fsize) +"</b> Too big Image file! 
Please reduce the size of your photo using an image editor.");
   return false
  }</p>
<p> }
 else
 {
  $(output_div).html("Please upgrade your browser, because your current browser lacks some new features we need!");
  return false;
 }
}
function bytesToSize(bytes) 
{
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Bytes';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function afterSuccess(fieldName)
{
 $('#submit-btn').show();
 $('#loading-img').hide();
 $('input[name='+fieldName+']').val('');
}
</script></p>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<div id="upload-wrapper">
<div align="center">
<h2>Ajax Image Upload and Resize with jQuery and PHP ( Multiple Input Fields) - Tobby News Demo</h2>
<form id="MyUploadForm" action="processupload.php" enctype="multipart/form-data" method="post">
<div class="field"><input id="ImageFile_1" type="file" multiple="multiple" name="ImageFile_1" /><br />
<img id="loading-img" style="display: none;" alt="Please Wait" src="images/ajax-loader.gif" />Field 1</p>
<div id="output_1"></div>
</div>
<div class="field"><input id="ImageFile_2" type="file" name="ImageFile_2" /><br />
<img id="loading-img" style="display: none;" alt="Please Wait" src="images/ajax-loader.gif" />Field 2</p>
<div id="output_2"></div>
</div>
</form>
<div class="clear"></div>
</div>
</div>
<p>

How to Set the input Fields.

We are working on dynamic fields so we have to name the input fields in a global method.
To display the Ajax uploaded images, a separate div tag should be created with id “output_(field number)”
Sample input fields with Jquery integration *

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
<br />
<!-- If Input fields name will starts with "ImageFile" name and id of the input field should be the same--><br />
<!-- Check this example--><br />
<!-- for input field one--><br />
<input id="ImageFile_1" type="file" name="ImageFile_1" /><br />
<!-- uploaded ajax image div have to be for input field one--></p>
<div id="output_1"></div>
<p><!-- for input field two--><br />
<input id="ImageFile_2" type="file" name="ImageFile_2" /><br />
<!-- uploaded ajax image div have to be for input field two--></p>
<div id="output_2"></div>
<p>

The ajax form will be forwarded to “processupload.php”

Select Code
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
<br />
<?php  
if((isset($_POST['fieldName'])))
{
$field_name=trim($_POST['fieldName']);
if((isset($_FILES[$field_name]['name']))&amp;&amp;($_FILES[$field_name]['name']!=''))
{
$field_only_name=$_POST['fieldName'];
$ThumbSquareSize = 200; // width for the thumbnail image. Helght will be calculated to avoid scaling of the image
$BigImageMaxSize = 500; // width for the banner image. Helght will be calculated to avoid scaling of the image
$ThumbPrefix = "thumb_";
$DestinationDirectory = 'uploads/'; // enter the upload folder
$Quality = 90;
if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
die();
}
if(!isset($_FILES[$field_name]) || !is_uploaded_file($_FILES[$field_name]['tmp_name']))
{
die('Something wrong with uploaded file, something missing!');
}
$RandomNumber = rand(0, 9999999999);
$ImageName = str_replace(' ','-',strtolower($_FILES[$field_name]['name']));
$ImageSize = $_FILES[$field_name]['size'];
$TempSrc = $_FILES[$field_name]['tmp_name'];
$ImageType = $_FILES[$field_name]['type'];
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES[$field_name]['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES[$field_name]['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES[$field_name]['tmp_name']);
break;
default:
die('Unsupported File!');
}
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
$thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName;
$DestRandImageName = $DestinationDirectory.$NewImageName;
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
   $op= '
<table width="100%" border="0" cellpadding="4" cellspacing="0">';<br />
   $op.='<br />
<tr>';<br />
   $op.= '
<td align="center">
<h3>Thumb Image</h3>
<p><img src="uploads/'.$ThumbPrefix.$NewImageName.'" alt="Thumbnail" class="thumb"></td>
<p>';<br />
   $op.= '</tr>
<tr>';<br />
   $op.= '
<td align="center">
<h3>Banner Image</h3>
<p><img src="uploads/'.$NewImageName.'" alt="Resized Image" class="banner"></td>
<p>';<br />
   $op.= '</tr>
<p>';<br />
   $op.= '</table>
<p>';echo $op;<br />
}<br />
else<br />
{<br />
die('Resize Error'); //output error<br />
}<br />
}<br />
}<br />
function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)<br />
{<br />
if($CurWidth &lt;= 0 || $CurHeight &lt;= 0)<br />
{<br />
return false;<br />
}<br />
//Construct a proportional size of new image<br />
$ImageScale = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);<br />
$NewWidth = ceil($ImageScale*$CurWidth);<br />
$NewHeight = ceil($ImageScale*$CurHeight);<br />
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);</p>
<p>// Resize Image<br />
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))<br />
{<br />
switch(strtolower($ImageType))<br />
{<br />
case 'image/png':<br />
imagepng($NewCanves,$DestFolder);<br />
break;<br />
case 'image/gif':<br />
imagegif($NewCanves,$DestFolder);<br />
break;<br />
case 'image/jpeg':<br />
case 'image/pjpeg':<br />
imagejpeg($NewCanves,$DestFolder,$Quality);<br />
break;<br />
default:<br />
return false;<br />
}<br />
//Destroy image, frees memory<br />
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}<br />
return true;<br />
}<br />
}</p>
<p>//This function corps image to create exact square images, no matter what its original size!<br />
function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)<br />
{<br />
//Check Image size is not 0<br />
if($CurWidth &lt;= 0 || $CurHeight &lt;= 0) { return false; } //abeautifulsite.net has excellent article about "Cropping an Image to Make Square bit.ly/1gTwXW9 if($CurWidth&gt;$CurHeight)<br />
{<br />
$y_offset = 0;<br />
$x_offset = ($CurWidth - $CurHeight) / 2;<br />
$square_size = $CurWidth - ($x_offset * 2);<br />
}else{<br />
$x_offset = 0;<br />
$y_offset = ($CurHeight - $CurWidth) / 2;<br />
$square_size = $CurHeight - ($y_offset * 2);<br />
}</p>
<p>$NewCanves = imagecreatetruecolor($iSize, $iSize);<br />
if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))<br />
{<br />
switch(strtolower($ImageType))<br />
{<br />
case 'image/png':<br />
imagepng($NewCanves,$DestFolder);<br />
break;<br />
case 'image/gif':<br />
imagegif($NewCanves,$DestFolder);<br />
break;<br />
case 'image/jpeg':<br />
case 'image/pjpeg':<br />
imagejpeg($NewCanves,$DestFolder,$Quality);<br />
break;<br />
default:<br />
return false;<br />
}<br />
//Destroy image, frees memory<br />
if(is_resource($NewCanves)) {imagedestroy($NewCanves);}<br />
return true;</p>
<p>}<br />
}<br />

in processupload.php at line no 8 and 9 change the sizes of your  images

Select Code
1
2
3
4
</p>
<p>$ThumbSquareSize = 200; // 200px<br />
$BigImageMaxSize = 500; // 500px</p>
<p>

 

Post By Praveen (38 Posts)

Website: →

Connect

About Praveen

Praveen S has written 38 post in this blog.

Leave a Reply