How to upload a file using Ajax on POST? - javascript

I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.
# html
<form method="post" id="Form" enctype="multipart/form-data">
{% csrf_token %} # django security
<input id="image_file" type="file" name="image_file">
<input type="submit" value="submit">
</form>
# javascript
$(document).on('submit', '#Form', function(e){
e.preventDefault();
var form_data = new FormData();
form_data.append('file', $('#image_file').get(0).files);
$.ajax({
type:'POST',
url:'my_url',
processData: false,
contentType: false,
data:{
logo:form_data,
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security
},
});
});
# views.py (server side)
def myFunction(request):
if request.method == 'POST':
image_file = request.FILES
...
...
I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.
Am I doing something incorrectly?

The below method works for me, it will submit all form value as serialize(). You will get all form input's inside request.POST and logo request.FILES
Try this:
$(document).on('submit', '#creationOptionsForm', function(e){
e.preventDefault();
var form_data = new FormData($('#creationOptionsForm')[0]);
$.ajax({
type:'POST',
url:'/designer/results/',
processData: false,
contentType: false,
async: false,
cache: false,
data : form_data,
success: function(response){
}
});
});
Update:
basically async:false will do ajax request and stop executing further js code till the time request get complete, because upload file might take some time to upload to server.
While cache will force browser to not cache uploaded data to get updated data in ajax request
Official Documentation here

Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
If you are using JQuery solely for the use of ajax, then I recommand using axios:
const axios = require('axios');
var formData = new FormData();
formData.append('imageFile', document.querySelector('#image_file').files[0]);
axios({
method: 'post',
url: 'your_url',
data: formData,
headers: {
"X-CSRFToken": CSRF_TOKEN, # django security
"content-type": "multipart/form-data"
}
}).then(function (response) {
# success
});
Axios Documentation
Jquery/Ajax answer:
var formData = new FormData();
formData.append('imageFile', $('#image_file')[0].files[0]);
formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security
$.ajax({
url : 'your_url',
type : 'POST',
data : formData,
processData: false,
contentType: false,
success : function(data) {
# success
}
});
Jquery/Ajax Documentation

Related

Is it Possible to Upload Image Using HTTP GET

I've been using the following code to upload image to server. Is it possible to change it to pass file data using an object instead of form data and using GET instead of POST.
var uploadfileinfo = document.getElementById("upload-file-info").value;
var file_data = $('#a_imgfile').prop('files')[0];
var a_imgfile = document.getElementById("a_imgfile");
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
async: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
alert(response);
},
error: function(err) {
alert(err);
}
});
Browser file upload will send form multipart contenttype, you cant send content type in GET request
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
If you are looking for some workaround you can use some base64 encoder and pass your image to url query param
In GET request you can only get data or pass query paramerters. If you want to upload image change any other data it must be in POST request
Read more https://www.w3schools.com/tags/ref_httpmethods.asp

Laravel cant read formData

I have been searching high and low for answers but I cant seem to find.
Trying to send file input to laravel controller via ajax but laravel controller can't seem to read the data at all
Following is my ajax code
let fd = new FormData();
fd.append('fwigNo' , $('#fwigNo').val());
fd.append('x' , 27);
formData = fd;
$('#submit').click(function(e) {
e.preventDefault();
url = url.replace(':vdrId', dataId);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT" ,
dataType: "json" ,
cache: false,
processData: false,
contentType:false,
url: url,
data: formData,
success: function(result) {
console.log(result)
},
});//end of ajax
})//end of submit
Following is my laravel controller
public function store($vdrId , Request $request)
{
dd($request->all());
}
I managed to send to form Data via ajax but when I dd($request->all()) , it shows empty
Please do advise
update:
Route shown in cmd
Thank you
in web.php route file,try use resource form method get request

Upload a CSV file using AJAX in Django

I want to upload a CSV file using ajax query.
Template:
<form id="attendance-form" method="POST" enctype="multipart/form-data">
<input type="file" id="upload-attendance" name="employee-attendance-file">
</form>
AJAX:
$("#upload-attendance").change(function(e) {
e.preventDefault(); // disables submit's default action
var input = $("#upload-attendance")[0];
var employeeAttendanceFile = new FormData();
employeeAttendanceFile.append("attendance-file", $('#upload-attendance')[0].files[0]);
console.log(employeeAttendanceFile);
$.ajax({
url: '{% url "attendance:employee-attendance-upload" %}',
type: 'POST',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},
data: {
"employee_attendance_file": employeeAttendanceFile,
},
dataType: "json",
success: function(data) {
data = JSON.parse(data); // converts string of json to object
},
cache: false,
processData: false,
contentType: false,
});
});
After uploading a CSV file, when I console.log the file variable (console.log(employeeAttendanceFile);) nothing returns. When I fetch the ajax request from django view, it also returns None (print(csv_file)).
# views.py
class ImportEmployeeAttendanceAJAX( View):
def post(self, request):
csv_file = request.FILES.get("employee_attendance_file")
print(csv_file)
What am I doing wrong?
When uploading data via a FormData object you have to pass it directly
data: employeeAttendanceFile,
Also, the name you set for the file in the upload has to match when you try to access it.
csv_file = request.FILES.get("attendance-file")

Sending a file in jquery ajax POST Api call

Using Jquery, when i try to call external API by sending any file. I'm facing 415 Unsupported Media Type error. I'm trying to send my document using FormData() and header data in beforeSend() function. Suggest me correct way of sending data.
<div id="folder-browser">
<input type="file" id="file-select" name="photos" />
<button id="myButton" value="click me">click me</button>
</div>
$("#myButton").click(function() {
var myData = new FormData();
var myFile = document.getElementById("file-select");
myData.append(myFile.files[0].name, myFile.files[0]);
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic c3lzYWRtaW46cGFzc3dvcmQtMQ==');
},
type: 'POST',
success: function(result) {
console.log(result);
return result;
}
});
});
Query 2: If my document is present in URL. please let me know How can I pass the URL as a file source.
for Example:
filepath = 'http://seekvectorlogo.com/wp-content/uploads/2018/02/opentext-vector-logo-small.png';
I need to pass this file source to my external API.
When uploading binary data in a FormData object you need to set contentType: false:
$.ajax({
url: 'http://10.96.45.179/RightFax/API/attachments',
data: myData,
processData: false,
contentType: false,
// your other settings...
});

Submitting a form with a file using JQuery and AJAX

I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?
My HTML:
<form id="photo-form" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
<input type="submit" name="submit" value="submit/>
</form>
My JQuery:
$(document).ready(function() {
$("#photo-form").submit(function(e) {
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "uploadcover.php",
data: dataString,
async: false,
success: function(data) {
alert(data);
}
});
});
});
You can use FormData to upload file with data
Here is sample code
JQuery
$("#photo-form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "uploadcover.php",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
return false;
})
You can get it on PHP
PHP CODE
$Img = $_FILES['upload-new-input'];
You can see tutorial Uploading files with jquery ajax
Hope It helps you :)
You cannot access file directly.
You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload
Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.
More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

Categories