Upload Multiple Files with PHP and JQuery
Index.html
<html>
<head>
<title>Load files</title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myfiles').on("change", function() {
var myfiles = document.getElementById("myfiles");
var files = myfiles.files;
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.ajax({
url: 'load.php',
type: 'POST',
contentType: false,
data: data,
processData: false,
cache: false
}).done(function(msg) {
$("#loadedfiles").append(msg);
});
});
});
</script>
</head>
<body>
<div id="upload">
<div class="fileContainer">
<input id="myfiles" type="file" name="myfiles[]" multiple="multiple" />
</div>
</div>
<div id="loadedfiles">
</div>
</body>
</html>
load.php
<?php
$path="myfiles/";//server path
foreach ($_FILES as $key) {
if($key['error'] == UPLOAD_ERR_OK ){
$name = $key['name'];
$temp = $key['tmp_name'];
$size= ($key['size'] / 1000)."Kb";
move_uploaded_file($temp, $path . $name);
echo "
<div>
<h12><strong>File Name: $name</strong></h2><br />
<h12><strong>Size: $size</strong></h2><br />
<hr>
</div>
";
}else{
echo $key['error'];
}
}
?>
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;
});
ajax multiple file upload with php
You can pass multiple files using form data as below
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("label", "sound");
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})
Now pass fd
object in you ajax call it is working with my code
Send Multiple Files to PHP with Jquery and Fetch
Here is working code for you and tested as well.
You have few issues with formData
append. You are not doing any forEach for your file so so when you are sending the fetch request you formData only gets the last file.
To store multiple file you need to have an empty array which i have named as filesToUpload
This array will store all the file which you will select on change function.
Once the array contains all the files you want to upload. On form submit function you will loop through that filesToUpload
array and append all its data to formData
and send it via fetch request.
On the backend PHP
side when you var_dump($_POST)
OR var_dump($_FILES)
you will see all these files there.
Working fiddle Demo: https://jsfiddle.net/woft6grd/
In the demo when you go dev tools -> network you will see on form submit your request will have all the files you uploaded via input.
jQuery
$(document).ready(function() {
// Add input files to array
var filesToUpload = []
//On Change loop through all file and push to array[]
$('#inputId').on('change', function(e) {
for (var i = 0; i < this.files.length; i++) {
filesToUpload.push(this.files[i]);
}
});
// Form submission
$("#formId").on('submit', function(e) {
e.preventDefault();
//Store form Data
var formData = new FormData()
//Loop through array of file and append form Data
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i]
formData.append("uploaded_files[]", file);
}
//Fetch Request
url = '../php/submit.php';
fetch(url, {
method: 'POST',
body: formData
})
.then(function(response) {
return response.text();
})
.then(function(body) {
console.log(body);
});
})
});
HTML
<form id="formId" enctype="multipart/form-data" method="POST">
<div class="ds-row ds-file-upload-container ds-mar-b-2">
<div class="ds-col-xs-12 ds-col-md-6">
<label for="inputId" class="ds-button">Choose a file
<input type="file" class="ds-file-upload" name="upload[]" id="inputId" multiple="multiple" required>
</label>
</div>
</div>
<input type="submit" value="Upload" />
</form>
I have added comments to each code line as well to highlight as well.
Php ajax multiple file upload with new array
You are appending single file using this line of code myFormData.append('myFiles', file);
. You have to use this code myFormData.append('myFiles[]', file);
to send multiple file. Below is the code that i have implemented which can upload multiple files.
in your script place below code.
<script type="text/javascript">
$("#upload").change(function (event) {
var files = event.target.files;
var uploadingFile = [];
files = Object.values(files);
files.forEach(function (file) {
if (file.type.match('image')
|| file.type.match('application/vnd.ms-excel')
|| file.type.match('application/pdf')
|| file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
) {
uploadingFile.push(file);
}
});
var myFormData = new FormData();
uploadingFile.forEach(function (file) {
myFormData.append('myFiles[]', file);
});
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
data: myFormData,success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
});
</script>
And in your upload php code place below code.
$target_path = "uploaded_files/";
$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
$total = count($myFiles['name']);
for($i=0; $i<$total; $i++){
$ext = explode('.',$myFiles["name"][$i]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error multiple uploading the file, please try again! \n";
}
}
} else {
$ext = explode('.',$myFiles["name"]);
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
echo "The file has been uploaded successfully \n";
} else{
echo "There was an error uploading the file, please try again! \n";
}
}
Related Topics
Convert Latin1 Characters on a Utf8 Table into Utf8
How to Find the First and Last Date in a Month Using PHP
PHP Fatal Error: Call to Undefined Function Json_Decode()
Using Default Arguments in a Function
Passing an Array as Arguments, Not an Array, in PHP
Checking to See If One Array'S Elements Are in Another Array in PHP
Rebase Array Keys After Unsetting Elements
How to Locate the PHP.Ini File (Xampp)
Create Ini File, Write Values in PHP
How to Access PHP With the Command Line on Windows
Using PHP'S Swiftmailer With Gmail
How to Make a PHP Form That Submits to Self
Can File Uploads Time Out in PHP
How to Emulate a Get Request Exactly Like a Web Browser