upload multiple images with jquery ajax and process them with php
Note: I totally reviewed my answer and made it better!
HTML
First we make a traditional form without a confirm button. Instead we make a button.
<form enctype="multipart/form-data" id="myform">
<input type="text" name="some_usual_form_data" />
<br>
<input type="file" accept="image/*" multiple name="img[]" id="image" /> <sub>note that you have to use [] behind the name or php wil only see one image</sub>
<br>
<input type="button" value="Upload images" class="upload" />
</form>
<progress value="0" max="100"></progress>
<hr>
<div id="content_here_please"></div>
Javascript/jquery upload side
than here is the Javascript.. o yes and Jquery to upload the images and the other form data:
$(document).ready(function () {
$('body').on('click', '.upload', function(){
// Get the form data. This serializes the entire form. pritty easy huh!
var form = new FormData($('#myform')[0]);
// Make the ajax call
$.ajax({
url: 'action.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
//add beforesend handler to validate or something
//beforeSend: functionname,
success: function (res) {
$('#content_here_please').html(res);
},
//add error handler for when a error occurs if you want!
//error: errorfunction,
data: form,
// this is the important stuf you need to overide the usual post behavior
cache: false,
contentType: false,
processData: false
});
});
});
// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e){
if(e.lengthComputable){
//this makes a nice fancy progress bar
$('progress').attr({value:e.loaded,max:e.total});
}
}
PHP processing side
And for those who need the php side to do something with those images here is the php code to loop trough:
<?php
$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["img"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$succeed++;
// get the image original name
$name = $_FILES["img"]["name"][$key];
// get some specs of the images
$arr_image_details = getimagesize($_FILES["img"]["tmp_name"][$key]);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$mime = $arr_image_details['mime'];
// Replace the images to a new nice location. Note the use of copy() instead of move_uploaded_file(). I did this becouse the copy function will replace with the good file rights and move_uploaded_file will not shame on you move_uploaded_file.
copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);
// make some nice html to send back
$thegoodstuf .= "
<br>
<hr>
<br>
<h2>Image $succeed - $name</h2>
<br>
specs,
<br>
width: $width <br>
height: $height <br>
mime type: $mime <br>
<br>
<br>
<img src='./upload/$name' title='$name' />
";
}
else{
$error++;
}
}
echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';
if($error){
echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
}
echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];
echo $thegoodstuf;
?>
live demo at my dev web server which is not always online!
If you want to compress and resize
You need this class:
class SimpleImage{
var $image;
var $image_type;
function load($filename){
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if($this->image_type == IMAGETYPE_JPEG)
{
$this->image = imagecreatefromjpeg($filename);
}
elseif($this->image_type == IMAGETYPE_GIF)
{
$this->image = imagecreatefromgif($filename);
}
elseif($this->image_type == IMAGETYPE_PNG)
{
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=0777){
if($image_type == IMAGETYPE_JPEG)
{
$gelukt = imagejpeg($this->image,$filename,$compression);
}
elseif($image_type == IMAGETYPE_GIF)
{
$gelukt = imagegif($this->image,$filename);
}
elseif($image_type == IMAGETYPE_PNG)
{
$gelukt = imagepng($this->image,$filename);
}
if($permissions != false)
{
chmod($filename,$permissions);
}
return $gelukt;
}
function output($image_type=IMAGETYPE_JPEG) {
if($image_type == IMAGETYPE_JPEG)
{
imagejpeg($this->image);
}
elseif($image_type == IMAGETYPE_GIF)
{
imagegif($this->image);
}
elseif($image_type == IMAGETYPE_PNG)
{
imagepng($this->image);
}
}
function getWidth(){
return imagesx($this->image);
}
function getHeight(){
return imagesy($this->image);
}
function maxSize($width = 1920, $height = 1080){
if(($this->getHeight() > $height) && ($this->getWidth() > $width)){
$ratio = $height / $this->getHeight();
$newwidth = $this->getWidth() * $ratio;
if($newwidth > $width){
$ratio = $width / $newwidth;
$height = $height * $ratio;
$newwidth = $width;
}
$this->resize($newwidth,$height);
return true;
}
elseif($this->getHeight() > $height){
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
return true;
}
elseif($this->getWidth() > $width){
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
return true;
}
return false;
}
function resizeToHeight($height){
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width){
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale){
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
if( $this->image_type == IMAGETYPE_GIF || $this->image_type == IMAGETYPE_PNG )
{
$current_transparent = imagecolortransparent($this->image);
if($current_transparent != -1) {
$transparent_color = imagecolorsforindex($this->image, $current_transparent);
$current_transparent = imagecolorallocate($new_image, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue']);
imagefill($new_image, 0, 0, $current_transparent);
imagecolortransparent($new_image, $current_transparent);
}
elseif($this->image_type == IMAGETYPE_PNG)
{
imagealphablending($new_image, false);
$color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $color);
imagesavealpha($new_image, true);
}
}
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
you can use it like this:
$succeed = 0;
$error = 0;
$thegoodstuf = '';
foreach($_FILES["img"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$succeed++;
$name = $_FILES["img"]["name"][$key];
$image = new SimpleImage();
$image->load($_FILES['img']['tmp_name'][$key]);
$chek = $image->maxSize();
if($chek){
$move = $image->save('./upload/'.$name);
$message= 'Afbeelding verkleind naar beter formaat!<br>';
}
else{
$move = copy($_FILES['img']['tmp_name'][$key], './upload/'.$name);
#$move = move_uploaded_file($_FILES['img']['tmp_name'][$key], './upload/'.$name);
$message= '';
}
if($move){
$arr_image_details = getimagesize('./upload/'.$name);
$width = $arr_image_details[0];
$height = $arr_image_details[1];
$mime = $arr_image_details['mime'];
$thegoodstuf .= "
<br>
<hr>
<br>
<h2>Image $succeed - $name</h2>
<br>
specs,
<br>
$message
width: $width <br>
height: $height <br>
mime type: $mime <br>
<br>
<br>
<img src='./upload/$name' title='$name' />
";
}
else{
$error++;
}
}
else{
$error++;
}
}
echo 'Good lord vader '.$succeed.' images where uploaded with success!<br>';
if($error){
echo 'shameful display! '.$error.' images where not properly uploaded!<br>';
}
echo 'O jeah there was a field containing some usual form data: '. $_REQUEST['some_usual_form_data'];
echo $thegoodstuf;
I'm trying to upload multiple images using AJAX and PHP but there is an error
Try passing the form element to FormData. No need to call the append method afterwards.
var files = $('form')[0];
var form_data = new FormData(files);
By using the append() method, you are putting a [object FileList]
in the $_POST array under the file_upload
key
If you just want the files from the form, you would need a loop:
var files = $('#file_upload')[0].files;
var form_data = new FormData();
for (var i = 0; i < files.length; i++) {
form_data.append("file_upload[]",files[i]);
}
How to upload multiple images to a folder using ajax php and jquery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload Iamge</title>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
//following code is working fine in for single image upload
// var files = $('#file')[0].files[0];
// fd.append('file',files);
//this code not working for multiple image upload
var names = [];
var file_data = $('input[type="file"]')[0].files;
// for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
/*var ins = document.getElementById('file').files.length;
for (var x = 0; x <ins; x++) {
fd.append("file", document.getElementById('file').files[x]);
}*/
$.ajax({
url:'upload.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$("#img").attr("src",response);
}
},
error:function(response){
alert('error : ' + JSON.stringify(response));
}
});
});
});
</script>
</head>
//HTML Part
<body>
<div class="container">
<h1>AJAX File upload</h1>
<form method="post" action="" id="myform">
<div>
<img src="" id="img" width="100" height="100">
</div>
<div>
<input type="file" id="file" name="file" multiple="multiple" />
<input type="button" class="button" value="Upload"
id="but_upload">
</div>
</form>
</div>
</body>
</html>
have made changes in below code
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
fd.append('file[]',names);
And there are also changes in PHP code
<?php
/* Getting file name */
//without loop working fine
$count = count($_FILES);
for ($i = 0; $i < $count; $i++) {
$filename = $_FILES['file_'.$i];
/* Location */
echo $location = "upload/".$filename['name'];
/* Upload file */
if(move_uploaded_file($filename['tmp_name'],$location)){
echo $location;
} else {
echo 0;
}
}
?>
count of files and file name are comming in a different way so I have made the changes as required instead of if gives file array like $_FILE['file_0']
,$_FILE['file_1']
and so on, I have also change the permission of upload directory please check if your directory have read and write permission (777) or not, this code works for me you can try I hope it will work for you also :-)
Upload multiple image using AJAX, PHP and jQuery
Try utilizing json
to upload , process file
object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/
How to upload multiple files using PHP, jQuery and AJAX
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
How to upload multiple image with Ajax?
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Ajax
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
})
Source : How to upload multiple files using PHP, jQuery and AJAX
Related Topics
Simple Form Not Sending Data via _Post
Isset() Function Is Returning True Even When Item Is Not Set
How to Format Numbers to Have Only Two Decimal Places
Insert Non-English Decimal Points in MySQL
Check If a "Run-Time" Multidimensional Array Key Exists
PHP Sessions Login with Remember Me
Replace &Nbsp; Characters That Are Hidden in Text
How to Easily Remove the Last Comma from an Array
What Is Unexpected T_Variable in PHP
How to Get List of Defined Namespaces
Using Preg_Split with Multiple Spaces
Tell Selinux to Give Apache Execute Access to PHP Files Outside Document Root
Group Subarrays by One Column, Make Comma-Separated Values from Other Column Within Groups
Minimum Cart Amount for Specific Product Categories in Woocommerce
Cannot Use Concatenation When Declaring Default Class Properties in PHP