$_FILES empty when upload multiple files with FormData from Ajax - javascript

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);
});

Related

Multiple File Upload using AJAX in sequence/queue

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);
}
});
}

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
})
}
})
})

How to send files and text with ajax

I have this code that uploads files to server but there is still one thing that I don't know how to fix.
var form_data = new FormData();
var ins = document.getElementById('upload-computer').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('upload-computer').files[x]);
}
$.ajax({
url: 'upload_file.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (res) {
if(res){alert(res);}
console.log(form_data)
}
});
My problem is that in data part of ajax request if I add another value like this:
data: form_data + '&name='+someVar,
...it won't work. How to make this work? And I don't use form.
you should add the new elements to the formData object like this
formData.append("name", "someVar");

ASP NET upload image with jQuery and AJAX

What I'm trying to do is theoretically simple: I want upload an image using ASP.NET, jQuery and AJAX, without submitting a form (this part is important).
So I have this:
HTML
<input type="file" accept="image/*" id="imguploader">
jQuery
var file_data = $("#imguploader").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
$.ajax({
type: "POST",
url: '#Url.Action("InsertImage", "Product")',
data: { file: form_data },
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
}
});
Controller
public ActionResult InsertImage(HttpPostedFileBase file) {
//blabla and the code to insert in the database.
return Content("");
}
What else I have tried:
// instead of using FormData, I tried to direclty capture the file using these:
var file = $("#imguploader").file;
//and
var file = $("#imguploader")[0].files;
//Same result (null).
The problem is that the file variable is always null no matter what. What I'm doing wrong? Can anybody helps?
You can manually set the FormData keys and values yourself.
<input type="file" name="imguploader" id="imguploader" />
<button id="btnUpload">Upload</button>
Create FormData and set a new key/value
$("#btnUpload").on("click", function(e) {
e.preventDefault();
var file = $("#imguploader").get(0).files[0];
var formData = new FormData();
formData.set("file", file, file.name);
$.ajax({
url: '#Url.Action("InsertImage", "Product")',
method: "post",
data: formData,
cache: false,
contentType: false,
processData: false
})
.then(function(result) {
});
});
The controller
[HttpPost]
public ActionResult InsertImage(HttpPostedFileBase file)
{
}

Multiple File Upload Ajax Request Issue

This currently works to upload one file, however when I try to upload more than one file it doesnt work, and it only uploads the first selected file from the browse button. Please help on how to make this accept multiple files selected?
function makeProgress(number){
var url = getRelativeURL("web/fileUpload");
var formData = new FormData();
formData.append('number', number);
formData.append('file', $('input[type=file]')[0].files[0]);
console.log("form data " + formData);
$.ajax({
url : url,
data : formData,
processData : false,
contentType : false,
type : 'POST',
success : function(data) {
FileUploadVisible(true);
$('#attachmentModal').modal('hide')
$(':input','#attachmentModal').val("");
$("#pbarmain").hide();
$("#pbar").hide();
$("#actionPlanDiv").hide();
setObjectEnabled('#Upload',false);
},
error : function(err) {
FileUploadErrorVisible(true);
}
});
}
Thanks!
you have to create an object of the formdata and append the files input to it, using a files[] object in a loop...
fd = new FormData();
fls = document.getElementById('uplfiles').files; //length of files...
for(j=0;j<fls.length;j++){
fd.append('files[]', fls[j]); //note files[] not files
}
where 'uplfiles' is the name of the files field, replace it with yours...
this should work, thank me later..
This is what worked for me.
HTML
<input type="file" id="my_uploads" multiple>
JS
// upload img
$('#my_uploads').on('change', function(e) {
var formData = new FormData();
var files = $('#my_uploads').prop('files');
$.each(files, function(i, file) {
formData.append('my_uploads', file);
$.ajax({
type: 'POST',
url: 'process-upload.php',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response){
console.log(response);
},
error: function(err){
console.log(err);
}
})
});
});

Categories