Upload a file with Ajax, jQuery and Laravel [duplicate] - javascript

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

Related

Php Ajax file upload, always getting undefined index error

Submitting file through ajax not working. I have followed other posts to create this but it appears formdata is not containing the file as a result i always get the error of undefined index 'image'
<form enctype: 'multipart/form-data'>
<div class="add_category">
<label style="font-size:20px;">Add categories</label>
<input type="text" name="category" id="category" placeholder="Enter Here" style="border-style:solid;height:30px;">
<label style="font-size:20px;">Choose image</label>
<input type="file" id="file" name="image" style="border-style:solid;height:25px;">
<button name="add_category" type="button" onclick="addcategory()" >ADD Category</button>
</br>
</br>
</div>
</form>
function addcategory(){
//var1=document.getElementById("category").value;
var formData = new FormData();
formData.append('image', $('input[id=file]')[0].files[0]);
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
enctype: 'multipart/form-data',
data : formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success : function(data) {
alert(data);
}
});
}
performcategoryserver.php:
<?php
$imagename=$_FILES['image']['name'];
echo($imagename);
?>
This always return undefined index image error ,please help.
Change
<form enctype: 'multipart/form-data'>
to
<form id="myform" enctype= 'multipart/form-data'>
Change your function to:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
$.ajax({
url : 'performcategoryserver.php',
type : 'POST',
data : formData,
async : false,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType:"json",
success : function(data) {
alert(data);
}
});
}
Your form tag opened in wrong way firstly can you fix that and try again ?
<form enctype: 'multipart/form-data'>
Should be
<form method="post" enctype="multipart/form-data">
Finally found the working code,
Changed this:
<form id="myform" enctype= 'multipart/form-data'>
Changed this:
function addcategory(){
var formData = new FormData( $("#myform")[0] );
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'performcategoryserver.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
alert(xhr.responseText);
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
}

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

upload image in Laravel before submitting form using ajax

I have written some watermark code in Laravel and it is working fine. But now I want to show the preview before submitting the file. But I am getting error "POST 419 (unknown status)"
My view source code is
<form class="form-horizontal" method="POST" action="{{ route('announcement.store') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<label for="description">Description</label>
<textarea id="my-editor" class="textarea" name="description" ></textarea>
<label for="image">Featured Image</label>
<input type="file" id="image" name="image">
<button type="submit" class="btn btn-success">Submit</button>
</form>
Javascript code
$(document).ready(function() {
$("#image").change(function(e) {
var image = $('#image').val();
$.ajax({
type: 'POST',
url:'{{url('/my-admin/imageupload')}}',
data: {image:image},
success: function( msg ) {
alert(msg);
},
error: function( data ) {
alert(data);
}
});
});
In this code, when I change the image I get error. I have done some watermark on image and save that image in folder. Now, I need to show that image on preview before submitting the form.
Image will not be sent with this "var image = $('#image').val();" piece of code while using ajax request as you need to use data = new FormData(); for image.
You missed _token as data to submit on ajax, so change the data to
data: {
"_token": "{{ csrf_token() }}",
"image":image
},
I have successfully uploaded the image by this code.
$("#image").change(function(e) {
var data = new FormData();
data.append('image', $('input[type=file]')[0].files[0]);
data.append('_token', "{{ csrf_token() }}");
$.ajax({
url:'{{url('/my-admin/imageupload')}}',
type: 'POST',
data : data,
enctype : 'multipart/form-data',
contentType: false,
processData: false,
success: function( data ) {
var baseUrl = "{{asset('')}}";
var imageUrl = baseUrl + data.msg;
$('#changeimage').html('<img src="'+ imageUrl +'" height="120px" width="150px">');
},
error: function() {
alert('unable to insert watermark on image');
}
});
});

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