Multiple File Upload using AJAX in sequence/queue - javascript

I'm new to Javascript and jQuery. While uploading N number of files in the form, only the last file is uploaded N times,
I'm want to upload each file one at a time (Asynchronously) through AJAX request.
Below is my implementation:
$("#file-input").on("input", function() {
var formdata = new FormData(document.getElementById("file-catcher"));
$.each($("#file-input")[0].files, function (key, file){
formdata.append(key, file);
// This is to Inspecting each file
for(var pair of formdata.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
// Sending AJAX
$.ajax({
type: "POST",
data: formdata,
url: "/url/to/upload",
datatype: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
console.log(data); // Inspecting Response
},
error: function (error) {
console.log(error); // Inspecting Error if occured
}
});
});
});
<form method="POST" id="file-catcher" action="/url/to/upload" enctype="multipart/form-data">
<input type="text" name="fileCode" value="10">
<input type="file" id="file-input" name="file-input" multiple>
</form>

I would like to give credit to Chris G for guiding me to iterate through each file to create a queue and send files in the sequence.
const inputFile = document.getElementById('file-input');
// Iterating through each file and sending AJAX request
for (const file of inputFile.files){
var formdata = new FormData(document.getElementById("file-catcher"));
formdata.append("file-input", file);
$.ajax({
type: "POST",
data: formdata,
url: "/url/to/upload",
datatype: 'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
console.log(data);
},
error: function (error) {
console.log(error);
}
});
}

Related

$_FILES empty when upload multiple files with FormData from Ajax

The problem is that when I try to upload a single file the server gets the request and I see that $ _FILES actually contains the uploaded file.
On the other hand, when I try to upload more files, the request comes with $ _FILES completely empty.
<input type="file" name="images[]" id="images-input-file" accept="image/jpeg" multiple="multiple" hidden />
//In this case '$(this)' is the file input
var files = $(this)[0].files;
//Append data to Form Data
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append("file-" + i, files[i]);
}
$.ajax({
method: "POST",
url: "/server/fnc/upload-images",
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(res) {
console.log(res);
},
});
Maybe the best way to do this is to use the form submit like this:
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/server/fnc/upload-images",
data: new FormData(this),
contentType: false,
processData: false,
success: function(res){
console.log(res);
}
});
}));
else can you try this to test:
var formData = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
formData.append('file', file);
});

Php $_FILES is empty when upload with ajax

I have form with input for attachment:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
.....
<div class="templateDiv">
<span class="invoice_email_label">Email attachments:</span>
<input name="email_attachment[]" type="file" multiple="">
</div>
<div class="templateDiv">
<button id="send_invoice_btn" class="bigButton redButton">Send</button>
</div>
</form>
And js:
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
data.append('send_invoice_subject', sendInvoiceSubject);
....
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
if (data.msg === 'Error. This invoice number exists.') {
alert(data.msg);
} else {
...
}
},
error: function () {
alert('error');
}
});
I tested and seems it doesnt work. All data pass well, but not file.
When I print_r $_FILES it is empty. What is my error? Thanks.
it's work for me --
var form_data = new FormData($('#submitForm')[0]);
$.ajax({
url: "<?php echo base_url() . 'backends/update_documents' ?>",
type: "POST",
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (res) {
// console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(xhr);
}
});
you can try with cache: false
and mention for button, type="button"
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
First remove dataType: 'json' Then if it still shows error then replace
data = new FormData($("#sendInvoiceForm")[0]);
with
data = new FormData($("#sendInvoiceForm").prop('files')[0]);
try to send the data via :
data: $('#sendInvoiceForm').serialize();

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

I have following html
<form id="submit-form">
<input type="file" id="resume" name="resume[]" class="inputFileHidden" multiple>
<input type="submit">
</form>
I am uploading files using ajax using formdata. The thing is that I don't want to send all files in one go using ajax. Instead I want to send single file per ajax request.
To upload files I am using following jQuery code
$('#submit-form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var url = "upload-files.php";
$.ajax({
url: url,
type: 'post',
data: formData,
success: function(response) {
alert(response);
},
cache: false,
contentType: false,
processData: false
})
})
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
})
}
})
})

Sending formdata for file upload using ajax

I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.
<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>
But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.
HTML
<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">
Jquery
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Below is the code i am using for saving the image.
exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
res.status = 500;
res.message = err;
// return res.status(500).send(err);
return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};
When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.
I think you have to create FormData, after you can append the file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = new FormData();
formData.append('file',$('#uploadFile')[0].files[0]);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
});
use
$("#uploadForm").submit(function () {
var formData = new FormData(this);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "/tab10/uploadImage",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

How to pass selected file to php script using jQuery?

The following form is what I use:
<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
<input name="attachment" type="file" />
<input type="submit" />
</form>
This is what I do with jQuery:
$('body').on('submit', '#form-attachment', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log('fine', data);
var url = 'imageupload.php';
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
console.log('success: ' + response);
},
complete : function(response) {
console.log('complete: ', response);
},
error: function(response) {
console.log('error: ', response);
}
});
});
And this is my imageupload.php file:
$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);
And this is result on console on submit():
success: {"c":false}
So, what is wrong? Why my file is not visible at all?
You can use FormData object, as shown below..
$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
jQuery.ajax({
type: "post",
contentType: false,
processData: false,
url: jQuery(this).attr('action'),
dataType: "json",
data: data,
success: function (r) {
// Success Handeling
}
});
});
NOTE:- No need to append anything as other answer suggests.
This method shall pass all the input fields just like they would in a normal http form POST method.
Use FormData object.
Here's the example how to send file via jQuery ajax request:
$(document).on('change', 'input[type=file]', function() {
formData = new FormData;
formData.append('file', $(this)[0].files[0]);
$.ajax {
url: '/upload-url',
data: formData,
type: 'post',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
}
});
In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.

Categories