How to Upload Multiple Files Using PHP, Jquery and Ajax

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

upload multiple files with ajax and jquery

After document is ready add a variable:

var fileCounter = 0;

Pass it to the first parameter of the append method, then increment.

$.each($(".project_image")[j].files, function (i, file)
{
data.append(fileCounter, file);
fileCounter++;
});

The problem is that you sent two files with the same name in POST request. You can see this by opening the ajax request and click the POST tab in Firebug. It was something like this for both files, so every next file overrides the previous one:

Content-Disposition: form-data; name="0";

EDIT: It exists a simpler solution just by pass a j as a first parameter of append without a clutter:

for(var j=0 ; j<= count ; j++)
{
$.each($(".project_image")[j].files, function (i, file)
{
data.append(j, file);
});
}

EDIT 2

It can also be done by using multiple attribute of a file input. It wouldn't be neccessary then to add other inputs, but just send them in only once.

HTML:

<form name="ajax_image" id="ajax_image" method="post" enctype="multipart/form-data">
<input type="text" name="project_name" id="project_name" placeholder="Project Name" /><br/><br/>
<input type="text" name="project_duration" id="project_duration" placeholder="Project Duration" /><br/><br/>
<input type="file" name="project_images" class="project_images" placeholder="Project Image" multiple /><br/><br/>
<input type="submit" name="submit" id="submit" value="Submit" />
</form>

JS:

$(document).ready(function () {
$("#ajax_image").submit(function (event) {
var data = new FormData();

event.preventDefault();

$.each($(".project_images")[0].files, function (key, file){
data.append(key, file);
});

$.each($('#ajax_image').serializeArray(), function (i, obj) {
data.append(obj.name, obj.value)
});

$.ajax({
url: "upload.php",
type: "POST",
data: data,
processData: false,
contentType: false,
success: function () {
alert('Form Submitted!');
},
error: function () {
alert("error in ajax form submission");
}
});
});
});

Upload multiple file using codeignter with ajax jquery

View Code:-

<body>
<p id="msg"></p>
<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
<button id="upload">Upload</button>
</body>

Ajax / jQuery Code:-

<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'ajaxmultiplefileupload/upload_files', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>

Controller:-

class AjaxMultipleFileUpload extends CI_Controller {

function __construct() {
parent::__construct();
}


function upload_files() {
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
echo 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $_FILES["files"]["name"][$i]);
echo 'File successfully uploaded : uploads/' . $_FILES['files']['name'][$i] . ' ';
}
}
}
} else {
echo 'Please choose at least one file';
}
}

}

jQuery AJAX multiple files upload but send one file at a time to server using ajax

You can just use forEach method of FormData:

$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";

formData.forEach(function(entry) {
if (entry instanceof File) {
var fileForm = new FormData()
fileForm.append('resume', entry)

$.ajax({
url: url,
type: 'post',
data: fileForm,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
}
})
})

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'];
}
}
?>


Related Topics



Leave a reply



Submit