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);
});
});
Related
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);
}
})
});
});
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
});
This question already has answers here:
How to upload a file using jQuery.ajax and FormData
(2 answers)
Closed 3 years ago.
I am trying to upload a form with jQuery and Ajax using Laravel as server side code, my form is:
HTML:
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Comprobante</label>
<input type="file" name="file" class="form-control" id="file" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nombre</label>
<input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter name">
</div>
</form>
jQuery, Ajax:
$( 'body' ).on( "submit", 'form', function() {
event.preventDefault();
var formData = new FormData();
formData.append("file", $('#file')[0].files[0]);
formData.append("name", $('#name').val());
var formData = $(this).serialize();
$.ajax({
type:'POST',
url:"{{ url('/accountability/store') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
success:function(html)
{
alert('stored!');
}
});
});
Laravel:
$extension = $request->file('file')->getClientOriginalExtension();
$filename = $request->rut.'_rendicion_'. date('d_m_Y_h_i_s') .'.'.$extension;
Storage::disk('dropbox')->putFileAs(
'/intranet_jisparking_archivos_web/',
$request->file('file'),
$filename
);
The problem is that it says that
Call to a member function getClientOriginalExtension() on null
But I do not understand why? because I am uploading the file with this $('#file')[0].files[0] in the jQuery. It looks like $request->file('file') is empty, how can I fix it?
Thanks!
Try this:
var formData = new FormData();
var file = $('#file').prop('files')[0];
formData.append('file', file);
formData.append('other_variable', $('#other_variable').val());
// Don't use serialize here, as it is used when we want to send the data of entire form in a query string way and that will not work for file upload
$.ajax({
url: '{{ url("your_url") }}',
method: 'post',
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response){
// Do what ever you want to do on sucsess
}
});
In controller method, you will get the file like:
$file = Input::file('file');
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]);
});
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.