How to Upload multiple images jQuery Ajax using PHP
I have received many requests from my readers to on how to upload multiple images in jQuery and PHP, so this is the article which I have wrote and explain jQuery and PHP to upload multiple images at once. You can use this as a reference for your web projects, specially focused on newbies to understand the procedures of images uploading.
Used a jQuery Library from hayageek.com and create tutorial in more simple way.
We also publish two tutorials on image upload
Here is index.html file which contain jQuery library and CSS to handle your requests.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <link href="css/uploadfilemulti.css" rel="stylesheet"> <script src="js/jquery-1.8.0.min.js"></script> <script src="js/jquery.fileuploadmulti.min.js"></script> </head> <body> <div id="mulitplefileuploader">Upload</div> <div id="status"></div> <script> $(document).ready(function() { var settings = { url: "upload.php", method: "POST", allowedTypes:"jpg,png,gif,doc,pdf,zip", fileName: "myfile", multiple: true, onSuccess:function(files,data,xhr) { $("#status").html("<font color='green'>Upload is success</font>"); }, afterUploadAll:function() { alert("all images uploaded!!"); }, onError: function(files,status,errMsg) { $("#status").html("<font color='red'>Upload is Failed</font>"); } } $("#mulitplefileuploader").uploadFile(settings); }); </script> </body>
<div id=”mulitplefileuploader”>Upload</div> This div will be replace with the form and input file field and make some are for drag and drop image. <div id=”status”></div> Shows status of images and progress of uploading images.
upload.php
File contains post upload process and move files in uploads directory.
<?php $output_dir = "uploads/"; if(isset($_FILES["myfile"])) { $ret = array(); $error =$_FILES["myfile"]["error"]; { if(!is_array($_FILES["myfile"]['name'])) //single file { $RandomNum = time(); $ImageName = str_replace(' ','-',strtolower($_FILES['myfile']['name'])); $ImageType = $_FILES['myfile']['type']; //"image/png", image/jpeg etc. $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt; move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $NewImageName); //echo "<br> Error: ".$_FILES["myfile"]["error"]; $ret[$fileName]= $output_dir.$NewImageName; } else { $fileCount = count($_FILES["myfile"]['name']); for($i=0; $i < $fileCount; $i++) { $RandomNum = time(); $ImageName = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i])); $ImageType = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc. $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt; $ret[$NewImageName]= $output_dir.$NewImageName; move_uploaded_file($_FILES["myfile"]["tmp_name"][$i],$output_dir.$NewImageName ); } } } echo json_encode($ret); } ?>
First check directory and error after that check if single file coming then process separate if multiple files handle in loop.
$RandomNum = time(); $ImageName = str_replace(' ','-',strtolower($_FILES['myfile']['name'][$i])); $ImageType = $_FILES['myfile']['type'][$i]; //"image/png", image/jpeg etc. $ImageExt = substr($ImageName, strrpos($ImageName, '.')); $ImageExt = str_replace('.','',$ImageExt); $ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName); $NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
Add UNIX time stamp with image name to create unique name.
This tutorial contain code to download and a demo to show how it work i hope you like this please feel free to comment.
Tutorial Categories:
social button is overlapping the input field in your demo, makes it unusable 🙁
It looks fine to me what browser you are using?
Good article!
I will use this functionality to develop Prestashop Modules.
Can you get me demo?
Vey Good
i can’t download it
i tried saving multiple images to my database table (using your code above ) for particular ID but i was not able to insert that id (passed in URL) in table . could you please help ?
did you get any answer? 🙂
how to save the details (filename and file path) of those files being uploaded in the database. please help
how to get demo code
Click on download code button and it will take you to the download page if you are a subscriber then enter that email it will give you download link. Not subscribed yet then subscribe now.
Click on download code button and follow the instructions.
download successfully
Nice, you have to wait 6 hours after subscription to be able to download. Guess I will unsubscribe then.
Hi, May I please know how can I modify your code to have limit of uploading only 5 images. Reply asap
edit your plugin settings and add this
.
Thank you for sharing your code, How can I limit the file size ?
6 hours to confirm the subscribing !!!!!!!!!
Incredibly frustrating sharing method my friend.
Have you guys never heard of “View Source”? You can download the files directly off of the server. Copy the code from the text above.
Thanks for the tutorial guys!
Hi, I want to ask how can alert a message and stop user from pressing the next button untill the progress is 100%.
You can disable your next button by default and make it active once upload complete in this function of your jQuery.
onSuccess:function(files,data,xhr){
// make button active
}
I already did what you said, but in case of multiple images. My button becomes active at first success of first image and for other cases it remains active.
Use this function in settings and add your button activate code:
afterUploadAll:function()
{
//All files are uploaded activate button
},
I tried what you said
afterUploadAll:function()
{
$(‘#submitBtn’).removeAttr(‘disable’);
},
but its not working my button is disabled and remains disable even after successful upload of images.
Sorry, my mistake I used the code but no effect it enables after upload of very first image and remains enabled.
Hi, thanks for updating your code. But I want to show alert if someone clicks on submit button when progress bar is not 100% that is image is not uploaded yet.
Hi, Is there any possible solution available????
Hey, I solved my problem. I used
onSelect:function()
{
//alert(“Wait untill image being uploaded !!”);
$(‘#submitBtn’).attr(‘disabled’,’true’);
$(‘#submitBtn’).addClass(‘disabled-button’);
$(‘.disabled-div’).css(‘display’,’block’);
},
I have updated the code and added trigger on all images upload, it will show an alert on all images upload please check above index.html script.
How can I modify it to show a thumbnail after uploading the image?
I want to upload zip of image folder and then unzip and store all images path with name in mysql db .please help
Thanks a lot for this tutorial.
Hi
I just want to pass file counter parameter to below function how it’s possible?
onSuccess:function(files,data,xhr)
{
//
}
Thanks,
Madan Kumar Ray
Hi. I want upload by button . I don’t want auto upload. Can you help me ?
You can use normal upload method
How i do?
How to disallow the user to upload image which is more than 1Mb?
How to implement size(Mb or Kb) restriction and image dimension restriction…?
For the max size restriction You make .htacces file in upload folder with this content:
php_value upload_max_filesize 10M
php_value post_max_size 30M
Should Show the thumbnail images after uploading the files
Should Show the thumbnail images after uploading the files ,pls make it little bit faster
Is it possible to pass another variable for example a gallery id $_POST[‘catId’];, I have tried but the upload function doesn’t seem to pick it up
Yes its possible you can post data by adding this line in settings:
formData: {"catId":"Mark Bagnall"},
And to make it as a posted value, would I put in $_POST[‘catId’] or use some form of javascript to populate the value?
have u noticed the issue with if (is_array) condition? It will never be considered as array even if u upload multiple images suggest me something to solve this?
I changed the “url” setting to this:
url: “updr/upload.php?P=” + document.getElementById(‘lstP’).value,
then I can use the $_GET[‘P’] variable in upload.php.
Great script thank you very much and works really well but can you
please advise how to restrict each image upload size to a maximum 2Mb.
if(!is_array($_FILES[“myfile”][‘name’])) is always not array of files although multiple files selected for upload??
thats right i am having the same issue even if you upload multiple images it will never consider it as array
hello i use your code but how i insert all value in my sql
db
may I wait almost 6 hours to download script?! bad done guys!
well, I may to wait, thanks anyway 🙂
What’s this?! I subscribed to the mailing list… but still not able to download. crap!
i don’t understand How can i change url : for use with codeigniter
how to disable the maxfilesize ??
Ur condition if(is_array(FILES[‘myfile’][‘name’])) never executes because it is never considered as array even when you upload multiple images so that is a bug in your program you should improve ur script
it doesn’t save files in the said directory ( ‘uploads’), How can i save file in directory or db?
Hi man, great tutorial!
I´ll use this to save users documents and need to save it on a MySQL database. How can I pass de user id to the php file?
THKS!
Hi did you solve this problem. Please can you explain. it.
Thank you
sir,it is great tutorial.but how to display it using php.
When open the index page, mulitplefileuploader div is hidden, but the form is not shown. What could be the problem? Excellent script 🙂
I cannot find where is mulitplefileuploader is made hidden. It is not in css, index.html nor js files.
Hello, I read your blogs. Your humoristic style is wonderful, keepdoing what you’re doing! And you can look our website http://refractory-brick.com/ about refractory brick manufacturer. Thank you very very much.
how can i do that with MYSQL?
you change the query into
$ret[$NewImageName]= $output_dir.$NewImageName; //these code not work well
$ret[‘fileName’]= $output_dir.$NewImageName;//change the line into these. it is associative array
mysqli insertion
———————–
$album=1;
foreach($ret as $key=>$value){
$sql=”INSERT INTO `image`(`album_id`, `image_url`) VALUES ($album,’$value’)”;
if (mysqli_query($con, $sql)) {
echo “New record created successfully”;
} else {
echo “Error: ” . $sql . ”
” . mysqli_error($con);
}
}
Hi, You are not doing server-side validation for image type, anyone can upload anythig, if they bypass jquery validation.
Hi! Is it possible that all images will be uploaded in email? Thanks!
thanks great full
it contain a small error
if you want to insert the data in to db table
you change the query into
$ret[$NewImageName]= $output_dir.$NewImageName; //these code not work well
$ret[‘fileName’]= $output_dir.$NewImageName;//change the line into these. it is associative array
mysqli insertion
———————–
$album=1;
foreach($ret as $key=>$value){
$sql=”INSERT INTO `image`(`album_id`, `image_url`) VALUES ($album,’$value’)”;
if (mysqli_query($con, $sql)) {
echo “New record created successfully”;
} else {
echo “Error: ” . $sql . “” . mysqli_error($con);
}
}
could not work 🙁
Hi, somehow this uploader is not working inside inbuilt browser of facebook android app.
Is there any way to solve this issue?
Hi Huzoor Bux,
How to delete file in file uploads?
I change ‘Done’ to ‘Delete’.
I used unlink but it doesn’t work anyway.
Have you any idea about this?
try this if(unlink(FILENME)){ echo “Deleted”; } else{ echo “Error”; } and make sure that you have given correct path of file to unlink.
Sir, below is my coding in upload.js and delete.php
/********************upload.js**************/
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
//alert(data[i])
$.post("branch/more_examples/delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
var hg2 =$('.stepContainer').height();
$('.stepContainer').height(hg2+65)
});
}
//pd.statusbar.hide(); //You choice to hide/not.
}
/************************end upload.js****************/
/*********************delete.php**********************/
include_once("../../Connections/dbConnect.php");
$conn=$db;
$dir = '/spk/dokumen/kenaikan_pangkat/';
$output_dir = $_SERVER['DOCUMENT_ROOT'].$dir;
if(isset($_POST["op"]) && $_POST["op"] == "delete" && isset($_POST['name']))
{
$fileName =$_POST['name'];
$filePath = $output_dir.$fileName;
if (file_exists($filePath))
{
unlink($filePath);
$qry="delete from dokumen_kenaikan2 where nama_fail like '%$fileName%'";
mysql_query($qry,$conn) or die(mysql_error());
}
echo "Deleted File ".$fileName."”;
}
/************************delete.php****************/
But Sir, I still having problem in deleting file in uploads file. There is any wrong in my coding?
try this if(unlink(FILENME)){ echo “Deleted”; } else{ echo “Error”; } and make sure that you have given correct path of file to unlink.
Can anyone help hot to insert the photos into the database with mysql. i try but is not work.
Please share your code so i can help you to fix that.
please avoid to insert the image directly into database 🙂
try this
$q=”insert into gallery(images) values(‘$ret[$fileName]’)”;
$result=mysql_query($q);
Your file looks fine.
What is the problem try to debug code line by line where your script stop.
Thanks Sir. May God Bless you.
My upload file finally works and success. i found that i forget to link your jquery.form.js.
Sir, if u dont mind, how i display back all file uploaded in my database?
For example, if i want to allow system to update file that have been uploaded, i have to display back the uploaded file.
I really appreciate if u give some tutorial about this. I’m newby in jquery. Your coding really helps me.
this code how mysql insert image system make. i need for my website ?id=1 for (5) < image added. id=1 page my add image view how.
my mysql insert code example:
new text added
New Text ADD Form
Head
message
Categories
<?php
$categories_cek = mysql_query("SELECT * FROM categories");
while($categories_cek_new = mysql_fetch_array($categories_cek)){
echo '’.$categories_cek_new[‘head’].”;
}
?>
<?php
break;
case "insertmysql":
$text_head = str_replace("'", "'", $_POST['txt_head']);
$text_message = str_replace("'", "'", $_POST['txt_message']);
$text_categories = $_POST['slct_categories'];
$date = date("d.m.Y");
if(($text_head == "") or ($text_message == "")){ // if empty alert!
echo 'alert(“Please no empty box!”);’;
echo ”;
}else{
$makale_kaydet = mysql_query(“INSERT INTO text (head,message,date,categories) VALUES (‘$text_head’,’$text_message’,’$date’,’$text_categories’)”);
echo ‘alert(“Text Added Successful!”);’;
echo ”;
}
break;
}
?>
sdff
hello sir this was so help full… i had one doubt from this topic …,if upload the image sucessfully after that how to know the image path ?
The image path will show ??
Hi,
I need to pass custom data on upload.php and then need to insert the file info into database as well as the custom data.
Please help…
Thanks!
Atiar
Hi,
I need to pass custom data on upload.php and then need to insert the file info into database as well as the custom data.
Please help…
Thanks!
Atiar
Hi How to upload Verot ?
Hi Im trying to make the upload base on submit but cant seems to get it .basically what im trying to to is 1. click upload to browse for img file then click start upload to trigger the ajax to work but i cant find a way to to it. can you pls help me a bit.
thanks
neil
Hi,
Thanks for the tutorial!
Is it possible to do a tutorial with the above code and uploading to an Amazon S3 bucket?
Thanks for your tutssss…
I am trying this script but the upload button does not work on my website, I am unable to click on the upload button as I would prefer to use that than drag and drop please, can anyone help me
I got the upload button working now but how can I get the page to refresh automatically after upload so I can see the images uploaded?
Sorry have got it all working perfect now
Hi, How can I limit the upload to 2 files at the same time? Default is 6 right?
Hi, How can I limit the upload to 2 files at the same time? Default is 6 right?
Huzoor buksh you are greaaaaaaattt
Huzoor buksh you are greaaaaaaattt
Huzoor buksh you are greaaaaaaattt
Huzoor buksh you are greaaaaaaattt
Huzoor buksh you are greaaaaaaattt
Huzoor buksh you are greaaaaaaattt
please i cant download
my email [email protected]
thank u so much
i upload 33 images which is 103mb most of file dosn’t upload please help
how we can define user roles in php
plz help me any body
how to upload multiple image into database ?
need multi video upload in wordpress…can u help?
How to perform an sql insert data with this one?
please tell me how crop image according height in image uploader.
Thank you VERY much!
everything working fine but it generates new form for every new file so if we use it within another form then jquery validation will stop working.
also cant upload mp3 file.
We can manage file size by ini file and hence file upload issue will solve, but there is still problem of multiple form generate….
how to add some description on each picture that I’ve select
how to add some description on each picture that I’ve select
how to add some description on each picture that I’ve select
Is it possible to set the maxfileupload limit to one.
i like it .thank you so much.
hi, redirect after upload is possible?
Hi there,
The script is perfectly fonctionnal but… I’d like to add 2 things and i can’t because i’m not a coder 🙂
First, I’d like to have a preview of the uploaded images instead of the name of it, like . I can’t find where this info is displayed in the .js file to replace it…
Finally, I’d like to add a php fuction to reduce the size, in pixels, of the uploaded images (maxfilesize). I’ve found many ways to do so but when I implant it ine the php code the upload doesn’t work anymore.
Thank you for helping.
great script, ty:)