Send FormData and string using one function - javascript

I want to send data from the form (file from input and string from input) using ajax to ASP.NET Function. If I send only files i use:
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: {files: formData },
processData: false,
contentType: false,
});
}
If I want to send an only string, I use:
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: { test: test},
dataType: "json",
});
}
It is possible to send string and FormData using one Ajax? I try something like this:
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: {files: formData, test: test },
processData: false,
contentType: false,
});
but now the string parameter is not sending (is null).
Additional - My Controller code
public async Task<IActionResult> UploadFiles(string test, IList<IFormFile> files)
{
...
}

It's not possible to combine multiple Content Types when sending a FormData object.
Append the string to the formData instance and set the name to test.
function readURL() {
var input = document.getElementById("fileUpload");
var files = input.files;
var formData = new FormData();
var test = "some text";
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
formData.append("test", test);
$.ajax({
type: "POST",
url: '/Apartment/UploadFiles',
data: formData,
dataType: "json",
processData: false,
contentType: false,
});
}

Related

how to upload all images from a folder

trying to upload all images from a folder
destination folder on server side is test
destination format for images is uniqid().jpg
problem - seems resulting array on server side is empty
<input type='file' class='inpfile' id='inpfo' webkitdirectory='' directory='' multiple='true'>
var inpfo = $('#inpfo');
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
fd.append('flist', flist);
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
contentType: 'multipart/form-data',
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
upload.php
$arr = $_FILES['flist']; //seems this is an empty array
foreach($arr as $el){
$tempname = $el['tmp_name'];
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}
You are passing a FileList object fd.append which is incorrect you have to loop through the list and add each file individually.
inpfo.on('change', function(){
var flist = inpfo[0].files;
var fd = new FormData();
for (let i = 0; i < flist.length; i++){
fd.append('flist[]', flist[i]); // add [] to denote array
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
async: false,
success: function (data){
console.log(data); // Undefined array key "flist"
},
cache: false,
contentType: false,
processData: false
});
});
You're using the array of files incorrect, see here
$arr = $_FILES['flist'];
foreach($arr['tmp_name'] as $tempname){
$uniq = uniqid();
$img = imagecreatefromjpeg($tempname);
$targ = 'test/' . $uniq . '.jpg';
imagejpeg($img, $targ);
}

Jquery AJAX with additional post parameters and FormData, don't call success on success

The way how I send the parameters work. The server does the right thing, and make a valid response with application/json.
But the success don't get called.
var fd = new FormData();
var filelist = $('input#Image').prop('files');
if (droppedFiles.length) {
for (var i = 0; i < droppedFiles.length; i++) {
fd.append('image' + i, droppedFiles[i]);
}
}
$.ajax({
url: './doUploadDisplayImage?_id=' + id,
type: 'POST',
data: fd,
processData: false,
contentType: false,
cache: false,
xhr: function () { // This is for tracking the upload status
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (evt) {
if (evt.lengthComputable) {
doProgressBar((evt.loaded / evt.total) * 100);
}
}, false);
return xhr;
},
success: function (res) {
res = JSON.parse(res);
// Don't get called
}
});

how to append multiple files input on formdata

I have to send multiple files using form data but my code is not working can anybody tell me where it is wrong.
$('#fileupload').on('change', function() {
var to_user_id = $(this).data('touserid');
var chat_id = $(this).data('chat_id');
var formData = new FormData();
$.each($('input[type=file]')[0].files, function(i, value) {
formData.append('file[' + i + ']', value.files[0]);
});
//console.log(formData);
formData.append('to_user_id', to_user_id);
formData.append('chat_id', chat_id);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
cache: false,
success: function(data) {
//console.log(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" name="upload_form" id="upload_form" enctype="multipart/form-data" action="upload.php">
<input type="file" name="fileupload[]" id="fileupload" multiple data-touserid="'+to_user_id+'" data-chat_id="'+getdata+'">
</form>
You have to pass the value in the form data
$.each($('input[type=file]')[0].files, function(i, value){
formData.append('file['+i+']', value); // change this to value
});
sample code which I used
$.each($('#upload_screenshot')[0].files,function(key,input){
formData.append('upload_screenshot[]', input);
});
Please implement below script code.
$('#fileupload').on('change', function(){
var to_user_id = $(this).data('touserid');
var chat_id = $(this).data('chat_id');
var form_data = new FormData();
var ins = document.getElementById('fileupload').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("documentfiles[]", document.getElementById('fileupload').files[x]);
}
if(ins > 0)
{
formData.append('to_user_id', to_user_id);
formData.append('chat_id', chat_id);
$.ajax({
url: 'upload.php',,
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
},
});
}
else
{
alert("Please choose the file");
}
});
I hope your problem will be resolved.

how to append serialize with formdata in ajax

I am tring to append serilize with formdata.It is not working.My controller as two viewmodel with httppostfilesbase as a parameter.i want to append both serilize collection with formdata and i went to send all data including file to controller.it is not working for me.can any one help on this please`
var fileData = new FormData();
if (window.FormData !== undefined) {
var fileUpload = $("#myFile").get(0);
var files = fileUpload.files;
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
}
}
var other_data = $('form').serializeArray();
fileData.append('file',other_data );
debugger
$.ajax({
type: "POST",
url: '#Url.Action("Save", "Settlement")',
data: fileData[0],
contentType: false,
processData: false,
success: function (result) {
if (result.redirectTo) {
} else {
$("#childcontent").html(result);
}
}
})
}
}
There is no need of fileData[0]. Change url to url: '/Settlement/Save',
Also check the console for any errors and revert if you need more information
Can you try with this?
$.ajax({
type: "POST",
url: '/Settlement/Save',
contentType: false,
processData: false,
data: fileData,
success: function(result) {
if (result.redirectTo) {
} else {
$("#childcontent").html(result);
}
},
});

formdata is not working in IE 9,10,11 Jquery

I want to upload file into server ,for this i am using ajax and formdata to upload in server,Everything is working fine in Chrome but not working in IE version 9,10,11.
var formdata = new FormData();
for (var i = 0; i < fileInput.files.length ; i++) {
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
if( fileInput.files.length>0){
$.ajax({
url:path,
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
},
error: function (err) {
return false;
}
});
}

Categories

Resources