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.

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
<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>
    <p>Each recommended image file size must be less than 1MB!</p>

    <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.

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
200
201
202
203
204
205
206
207
<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

35 Comments Add Comment

  • Interesting article . For my two cents , if someone wants to merge PDF files , my wife saw announcement herehttps://goo.gl/W5uFRb

     Reply
  • Hi,
    The code is great, could you please show how to insert image urls to a database using object-oriented php function?

    Please Help.

     Reply
  • Really Doing Grate Code,

    But one query how to insert this record in database
    if i have a 2 table
    product
    product_image

     Reply
  • 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

     Reply
  • hi
    i am not speak english good.
    pl help me.
    i want remove and delet the image after upload.
    code?

     Reply
  • 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.

     Reply
  • Nice tutor.
    But “Add More File” seem not well functioned. I got an error in firebug :
    ReferenceError: event is not defined.
    event.returnValue = false;

     Reply
  • Hi! Great code, I have implemented it on my website but I have a problem, I can only upload 2 images, do you know why is that? It uploads 2 images and their respective thumbnails, but nothing more. Thanks in advance.

     Reply
  • Hello there
    First, i would like to thank you for this tutorial it really helped me a lot on my project. But there’s one thing that doesn’t work, that query to insert data to database, it doesn’t work for me. Can you help me please? Thank you..

     Reply
  • hello,
    I used part of your script to upload more picture .. everything works but if I use it more than once I have $ _FILES that contains the names of the first time .. how can I clean the array of images every time?
    thanks for the help ..
    luca

     Reply
  • Please Let Me Know One More Thing:-What Will I Have To DO FOR—ADD MORE FILES To Work…

     Reply
  • Nice tutorial but I can’t view any progress bar

     Reply
  • I know this could be a naive question. But it still nags me:

    Is there any option to multi select files inside the file open dialogue by something like pressing shift button as normally can be done in windows explorer ?

    http://www.landshoppe.com/Thane

     Reply
  • Hello, thank you for the goot tutorial.
    I want to generate dynamically in addition to the upload field, the height, the width and the quality. That’s why I converted these fields in array and adapted to the javascript function. But I get this error message:
    Fatal error: Unsupported operand types in

     Reply
    • Here is an example
      Thumbnail
      Thumbnail size

      Big Image
      Big Image size

      Quality
      Quality of the Image

    • <?php
      1.Thumbnail (thumbnailsize[])
      2.Thumbnail size
      3.
      4.
      6. Big Image
      7. Big Image = (bigsize[])
      8.

      9. Quality of Image
      10. Quality[]
      11.
      12

      ?>

  • I am also getting this error
    Warning: imagejpeg(/websites/fbphoto/uploads/1161987189.jpg): failed to open stream: No such file or directory

     Reply
  • Thought I should mention that for Firefox you need to include ‘event’ in the code to add more files. Here in bold:

    1
    2
    3
     var i = $("#AddFileInputBox div").size() + 1;
                    $("#AddMoreFileBox").click(function <b>(event)</b> {
                        event.returnValue = true;
     Reply
    • Great, thanks!

    • But this code didn’t work at firefox. Not work clicking add more files at firefox

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      var i = $("#AddFileInputBox div").size() + 1;
      $("#AddMoreFileBox").click(function (event) {
              event.returnValue = true;
              if(i < MaxFileInputs)
              {
                  $('').appendTo(FileInputsHolder);
                  i++;
              }
              return false;
      });
    • just change like this:
      — code —
      $(“#AddMoreFileBox”).click(function(event)
      — code —

      :) great script, thanks for sharing!

  • Nice tutorial,it is working great ,keep it up.

     Reply
  • how would I be able to insert all the image names into a database?

     Reply
  • why i got this error…. need your help please

    Warning: imagejpeg(/websites/fbphoto/uploads/1161987189.jpg): failed to open stream: No such file or directory in C:xampphtdocsmultupload.php on line 146

     Reply
    • is the error message so without Slash? the words are not so separated?
      The Error Message must be so:C:\xampp\htdocs\multupload.php

      You must check your Path and your Settings

  • Great script – excellent documentation… Worked 1st time
    But you know we always want more – what can we do about file size limitations some of my users, okay most, don’t know or care about file size. Hence re-size and dump the full size image.

     Reply
  • Hi, how can i change the upload max size, in my php.ini its 20M. Can’t upload 6mb pictures.
    error: Error occurred while trying to process IMG_0001.JPG, may be file too big!

     Reply
  • I am trying to upload more than one image. But I am not able to upload. Could you please let me know why I am not able to upload. Is there any option where I can changes so that I would be able to upload more than one image.

     Reply
  • Hi

    Is it possible to add a “preview” funcion of a image when you click the “Choose file” button to this script? Meaning, so the image will be visible at once so the user can see it or then remove it before upload if he / she want?

    Is this all done on server side?

     Reply
  • There is a problem:

    $ThumbMaxWidth = 200; //Thumbnail width
    $ThumbMaxHeight = 200; //Thumbnail Height
    $BigImageMaxWidth = 500; //Resize Image width to
    $BigImageMaxHeight = 500; //Resize Image height to
    $ThumbPrefix = “thumb_”; //Normal thumb Prefix
    $DestinationDirectory = ‘/home/website/uploads/’; //Upload Directory
    $jpg_quality = 90;

    If you set the sizes (Width) to anyting above 500, the images width remains at 494px. Event if i change it to 1900px, it still comes to 494px.

     Reply
    • Hi, it tries to proportionally resize keeping aspect ratio of original image, if your original image is 2000×2000 and you have set 500px max height and 1900px max width, it will resize to maximum 500px height or width whichever is less.