Very few days back I had posted an article about Multiple ajax image upload without refreshing the page using jquery and PHP. In this post I have updated few lines of code that allows to user can select and upload multiple images in single shot, thanks to Lakshmi Maddukuri for sending me a useful piece of code. Just take a quick look this live demo.
Download Script Live Demo
Sample database design for Users.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
Javascript Code
$("#photoimg").on('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').on('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>
ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
} //foreach end
}
?>
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
} //foreach end
}
?>
db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
CSS
Style for image blocks.
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
Thanks :)
ReplyDeletebut how to remove selected images ...? in case of i dont want some images .what i do??
DeleteThanks for sharing, this is a good example for Ajax upload.
ReplyDeleteDropzone.js is another good script for multiple file upload.
when its necessary to use singleton and this connection?
ReplyDeletecoul'd you please maybe use mysqli in the future examples... i have a problem with singleton class =(
Please develop a ranking system for points
ReplyDeleteThe script can not be downloaded. Although I registered for Box but it says that you do not have permissions to download this file. Can you help? I am using the older version of this script on one of my websites and it's doing great!
ReplyDeletebox.com limit download.
ReplyDeleteYou can upload mediafire.com
oh man.. you are amazing :)
ReplyDeleteNice Lakshmi maddukuri thanks Srinivas tamada
ReplyDelete@Ahmad Rasheed Which country you from?
ReplyDeletenice
ReplyDeletethanks
ReplyDeleteThank you@srinivas Tamada
ReplyDeletethanks nice work..i have a questions?. does this code will work for cross domain
ReplyDeleteNice one. But didn't work for IE9. :-(
ReplyDeleteHi Srinivas, i am commenting first time for your post.i am a fan of your posts.it helps a lot..i needed this kind of functionality for one of my project and i want to extend it a bit more..that is how can i remove an uploaded image at the same time without refreshing the web page.?...Although i am trying to do this , however your guidance will always be appreciated..Thanks.
ReplyDeleteNice job...but can u add uploading process bar for all multiple image with its uploaded percentages on it? so that user can see the complete process?
ReplyDeleteGreat work
ReplyDeleteGreat article but dont work in IE :(
ReplyDeleteI usually using uploadify. But i thing your script is better, because pure Javascript, no need Flash. Thanks.
ReplyDeleteWeldone, this really help. try implement deleting of the images using check box.
ReplyDeleteFor version 1.9 of jQuery
ReplyDeleteIs it possible to use the function. On () instead of live. () Is deprecated
thanks
ReplyDeletethanks ....
ReplyDeleteThanks for d info..
ReplyDeleteVery nice and helpful tutorial. could we use drag and drop in this same code also??
ReplyDeleteNice Work Venkata Lakshmi(Suneetha) Keep it up....
ReplyDeleteGood work Venkata Lakshmi(Suneetha)Keep it up...
ReplyDeleteThis code has made my work easy! Thanks a lot Srinivas anna!! :)
ReplyDeleteThis script is beautiful! Worked perfect
ReplyDeleteThanks for sharing this amazing tutorial with us Srinivas . This post has helped me to learn something new today . I'll be trying this out for sure.
ReplyDelete-Pramod
Thanks for your share!
ReplyDeleteNice.. What about the same but with backbone, underscore and java?
ReplyDeleteWow!!! Very Nice thanks for sharing this with us.
ReplyDeletejQuery("#imageform").ajaxForm is not a function.
ReplyDeleteHelp me. because I have use jQuery to not conflict, so i dont use $
Thanks for this awesome script...it's realy helpfull.
ReplyDeleteAnd i have a suggestion: it would be great if you add "delete image" function ..
:)
Thank you very much
Hi! Thanks for this tute. I have an issue when uploading large files
ReplyDeleteI've got this error message: "Something went wrong."
I've checked the servers upload and post limits and are ok. Modified the Max upload size to 5mb, and still got the error.
hi,
ReplyDeletethe plugin is great but id doesnt work in IE (totally doent work) and Safari (if more than one picture is uploaded),is there any way around?
thx
Thanks for the tutorial !! I really like all your scripts !!
ReplyDeletehello , is it possible to limit the amount of image displayed ?
ReplyDeletethanks for tutorial!!!
ReplyDeletehow can i use javascript alert() function and show image url with alert()????
@Srinivas Tamada Hi As you are a great programmer I am requesting you to create a photo tagging script ... If you can please make it ... Thanks ...
ReplyDeleteI don't want to move files before submit form, but i still want to preview. How to do it?
ReplyDeleteMore a question: How to add field "title" and "description" for each images before submit form?
ReplyDeleteThank you!
thanks for this tut, maybe u can extend this script with a delete function :)
ReplyDeleteThanks you
ReplyDeleteThanks you!
ReplyDeletethanks
ReplyDeleteThanks Srinivas.It saves me hours of time to implement this kind of functionality in my website.
ReplyDeleteit works only for the first time but not for the next I dont know what is the mistake i am doing could anyone help me
ReplyDeleteGood Tutorial
ReplyDeleteGreat code............
ReplyDeleteGreat code, Thanks!!!
ReplyDeletei am using this code in my localhost, everything is working great.
*but sometimes the files are uploaded twice. it seems like its stuck into some kind of loop or the button is pressed twice. :S
this is great
ReplyDeleteHi:
ReplyDeleteNice tutorial and nice combination.
How can I avoid this error : TypeError: Cannot read property 'msg' of undefined
I tried with required and ng-minlength="1" but it does not work.
I want to avoid to insert an "undefined" record in the table, how cna I do that?
Best regards,
very nice. For Naveent here is the photo tag script:
ReplyDeletehttp://net.tutsplus.com/tutorials/php/creating-a-photo-tag-wall-with-twilio-picture-messaging-php/
works fine but its only store 1 image to mysql table...
ReplyDeleteI want to upload 5 images one by one ? Please tell me how to do this ?
ReplyDeletenice work but i have problem with Arabic name image can help me thanks
ReplyDeleteHi, please forgive me ignorance I'm very new to javascript. Is it possible to direct the images to different tags? Such as #preview1, #preview2, etc. I'm trying to put images in different table cells. I can put div preview1, preview2 etc in the table cells but can't get the images to go there. Thanks
ReplyDeleteThat really worked with mysql php just as i wanted ... thanx a ton :D
ReplyDeleteThanks for your support !!
ReplyDeleteHugs from Argentina !!
Thanks for your support !!
ReplyDeleteGan, javascript give me alert"Something wentaaa wrong"?? Please help me :((
ReplyDeletePlease Help. i have add Progress Bar this Script.
ReplyDeleteHi savita, i am having issues using this script with codeIgniter. can you help?
ReplyDeletethanks dude.you done a good job
ReplyDeletei have this script run the localhost than get this error
ReplyDeleteB
Hi, please forgive me ignorance I'm very new to javascript. Is it possible to direct the images to different tags? Such as #preview1, #preview2, etc. I'm trying to put images in different table cells. I can put div preview1, preview2 etc in the table cells but can't get the images to go there. Thanks
ReplyDeleteSorry frnd i am new in this professional so i cannot undestand this code which one is given below
ReplyDeletewhat is this $str and $l = strlen($str) - $i;
i know that strlen is used for find string length but now hun es vich kon se length find karne hai Plz help me
------
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
----
hi this is kumar...when i upload file in localhost it is showing something went wrong pop up can u please help me
ReplyDeleteGood post
ReplyDeletevery nice
ReplyDeleteLooking for this tutorial...!!!! Very Well written
ReplyDeleteBut I need to ask one thing that can we use dropzone.js with the code given in the post ?
very nice!!!!!
ReplyDeleteThis is very nice tutorial Do you have any Codeigniter related with this process
ReplyDeletehi how to upload upto 1000 files in one go thank you
ReplyDeletethanks
ReplyDeletethis is good..
ReplyDeletehi..this is good...but after i download your script and testing i got the alert as "something went wrong". Could you please help me...
ReplyDeleteI had the same issue. what i did to fix this issue is change localhost to 127.0.0.1 then it worked.
Deleteyou just check database file in his folder and update as per your database and create table in your database as this script required. this code run properly i checked..
ReplyDeleteI don't want to move files before submit form, but i still want to preview. How to do it?
ReplyDeleteThanks for your support
ReplyDeletecould you please tell me how to use this code in codeigniter .... where am I supposed to add "ajaxImageUpload.php".
ReplyDeletenice tutorial ...
ReplyDeleteSir i want to edit image from database . ... and update image in database plz help me
Thank you very much to shared
ReplyDeletewhy you don't use POO??
ReplyDeleteHow to delete an image ?
ReplyDelete@Ahmad Ghallab
ReplyDeleteUser unlink($image_path);
sir how i load docs and txt file along with photo
ReplyDeleteModify $valid_formats = array("jpg", "png", "gif", "bmp","jpeg"); add txt extension
Deleteplease add a photo(s) deletion feature.
ReplyDeletethis is good.
ReplyDeletethanks:)
ReplyDeletehow to upload multiple image into mysql table in single row
ReplyDeleteConvert image into Base_64, try this http://www.9lessons.info/2010/11/base64-encoding-for-images.html
DeleteVery Nice thanks for sharing this with us.
ReplyDeleteThanks for sharing, i like it
ReplyDeletei want to upload image using mobile , show error message " Aw, snap!
ReplyDeleteSomething went wrong while displaying this webpage
if you're seeing this frequently, try these suggestions"
desktop version working fine
http://www.9lessons.info/2013/09/multiple-ajax-image-upload-jquery.html
Please check on mobile
Very impressive and unique, I enjoyed it
ReplyDelete