Multiple files on FormData() append - javascript

I need to add an array of images in FormData, but only the first image is passing.
I know the problem is in the JS code because when I send the form direct to the php page, it works fine.
JavaScript
var url = $(this).attr('action');
var data = new FormData();
$.each($("input[type='file']")[0].files, function(i, file) {
data.append('image[]', file);
});
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
});
HTML
<label for="1">Image 1</label>
<input type="file" name="image[]" id="1"/>
<label for="1">Image 2</label>
<input type="file" name="image[]" id="2" />
<label for="1">Image 3</label>
<input type="file" name="image[]" id="3" />

For Vanilla JS, I like to use Array.from and loop through each element like this
let data = new FormData();
let input_file = document.querySelector('input[type="file"]')
Array.from(input_file.files).forEach((f) => {
data.append('image[]', f)
})

Try
jQuery.each(jQuery('input[type=file]'), function(i, value)
{
data.append('image['+i+']', value.files[0]);
});

Related

How to get file from an action method which is downloading

Here is my sample code which I got from a website which converts xls to xlsx. It downloads the file immediately after converting it to xlsx, so I want to use that file further as blob. so is there any way to use that file which I will receive from action method using JavaScript?
Thank you!
HTML Code :
<form action="https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&download=attachment" method="post" enctype="multipart/form-data">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="anyName" />
<input type="submit" value="Convert file"/>
</form>
JavaScript code:
function convert(input){
let obj = {
File : input,
FileName : 'Test'
}
$.ajax({
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=...&StoreFile=true',
method: 'POST',
headers:{
'content-type' : 'multipart/form-data'
},
body: JSON.stringify(obj),
success : function(res){
console.log(res);
},
error: function(err){
console.log(err.responseText);
}
})
}
you would use javascript's fetch() to upload the file to the conversion endpoint instead of using a form, then you would get the file download as a response, which you can do with what you like.
this question may help you figure out how to upload a file, but you will have to understand a bit of javascript:
How do I upload a file with the JS fetch API?
I tried to upload same way as you mentioned #dqhendricks but didn't worked for me.
when I tried with FormData it worked for me. It would be awesome if we could do it with just JS.
HTML :
<form method="post" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="File" />
<input type="hidden" name="FileName" value="newFile" />
<input type="button" id="btnSubmit" value="Convert file"/>
</form>
JS:
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
var form = $('#fileUploadForm')[0];
var d = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: 'https://v2.convertapi.com/convert/xls/to/xlsx?Secret=[Secret]&StoreFile=true',
processData: false,
contentType: false,
cache: false,
data: d,
timeout: 600000,
success: function (res) {
console.log(res);
},
error: function (err) {
console.log(err.responseText);
}
})
});
});

how to send form data in ajax with multiple files without refreshing?

in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});

How can i send file and more info same time in flask? [duplicate]

This question already has answers here:
How to use FormData for AJAX file upload?
(9 answers)
Closed 3 years ago.
i have this code for upload file to flask.
client side:
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn" type="button">Upload</button>
</fieldset>
</form>
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
if file and a
this code upload file and work. How can i send more info to flask same time ?like time = 2020 , age=20 , ...
i find my answer but i cant answer to my question, so i write my ans here:
i use header,send more info like id , ... with user (but this is unsafe):
client side:
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
form_data.append('username', 'Chris');
//form_data.append ('id',$('#upload-file')[0]);
console.log(form_data);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data, headers: {
'Id': 2528,'age':20
},
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
id=request.headers['Id']
age=request.headers['age']
Put the data in the form, then pass the form to new FormData instead of just the file input.
e.g.
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn">Upload</button>
</fieldset>
<input type=hidden name=time value=2020>
<input type=hidden name=age value=20>
</form>
and
$("form").on("submit", function (e) {
e.preventDefault();
const form = this;
const form_data = new FormData(form);
// etc
});

How to solve this jQuery ajax post method undefine index problem while uploading images?

I want to Upload photos by using Ajax Post method,
Here is my html and javascript code
<script>
$(document).ready(function(){
$('#multiple_upload_form').submit(function(e){
e.preventDefault();
var upload = $('#images').val();
$.ajax({
type:'POST',
url:'album.php',
data:
{
upload : images
},
cache:false,
contentType:false,
processData:false,
success:function(data)
{
$('#image_preview').html(data);
},
error:function()
{
$('#image_preview').html('error');
}
});
return false;
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="album.php" name="upload_form" id="multiple_upload_form" role="form" enctype="multipart/form-data">
<div class="form-group">
<label for="email">Album Name</label>
<input type="text" name="aname" class="form-control" id="aname">
</div>
<div class="form-group">
<label for="file">Upload Photos:</label>
<input type="file" id="images" name="images" />
</div>
<div id="images_preview"></div>
</div>
<center class="feedback" style="display:none">Loading...</center>
<button id="submit" name="submitt" class="btn btn-default">Submit</button>
</form>
and this is my PHP CODING
if(isset($_FILES['images']['name']) )
{
$img = $_FILES['images']['name'];
if(!empty($img))
{
echo 'MaxSteel';
}
}
else
{
echo 'Same Problem';
}
I am having undefine index : images
it works fine with input type="text" but when it comes to "file" type is shows error help me solving this problem
Go through this code, it may help
var data = new FormData();
data.append("Avatar", file.files[0]);
$.ajax({
url: "http://192.168.1.1:2002/,
type: "POST",
data:data,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
Its posible that the file is not upload becouse of some error. You should review the parameters related to file upload as UPLOAD_MAX_SIZE, etc.
You can use var_dump($file) to see the $_FILE content.
You need to be sending your data through FormData().
Try something like this:
var images = $("#images").get(0).files;
var formData = new FormData();
$.each(images, function(i, image) {
data.append("images[]", image);
});
Then send formData as your $.ajax data.

Simple FormData not working

I am trying to test a simple FormData object but its not working at all. jsfiddle: https://jsfiddle.net/8j80898h/
html code:
<form id="createForm" name="createForm" novalidate enctype="multipart/form-data">
<input type="hidden" name="name" value="Name1" />
<input type="file" name="file" />
<input type="button" id="submitIt" value="Submit" />
</form>
js:
$(document).ready(function() {
$('#submitIt').click(function() {
var fd = new FormData($('#createForm')[0]);
fd.append( 'name', $('input[name=name]').val());
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
});
Server is always getting null values for name and file
FormData has a get method you should use:
$(document).ready(function() {
$('#submitIt').click(function() {
var d = new FormData($('form')[0]);
alert(d.get('name'));
});
});
read more in MDN: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get
rather than making an FormData object you can access elements within an form like the code below shows :)
$(document).ready(function() {
$('#submitIt').click(function() {
var d = $('form').toArray();
alert(d[0].name);
});
});

Categories