Why is Flask not receiving my POST Blob? - javascript

My problem is that I'm sending a Blob to the server with FormData, but the server isn't getting it. Code looks like the following:
Flask server code:
#app.route('/save-record', methods=['POST'])
def save_record():
app.logger.debug(request.form.keys()) #Shows only the title key, not the file key
Client JS Code:
var save = function() {
var form = new FormData();
form.append('file', record.blob, record.filename);
form.append('title', searchedObj.title);
//Chrome inspector shows that the post data includes a file and a title.
$.ajax({
type: 'POST',
url: '/save-record',
data: form,
cache: false,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});

Check request.files for the file.
#app.route('/save-record', methods=['POST'])
def save_record():
app.logger.debug(request.files['file'].filename)

Related

How can I send a file and a string to my backend C# from JQuery Ajax?

My UI has one input for uploading file and one input for the file's name.
I want to get both file and its name from user at the same ajax request and upload the file with the gotten name to my server.
the question is how can I get both file (binary) and the file's name from user at the same request ?
here is my try but results in 400 error.
Function in C#:
public IActionResult UploadImage(IFormFile upload, string fileWithName)
{
//some code here
}
and here is my ajax:
$("#startUploading").on("click",function() {
var fileInput = $.trim($("#myfile").val());
var formData = new FormData();
formData.append('upload', $('#myfile')[0].files[0]);
formData.append('pathWithName', $("#fileAddressUploadTo").val());
$.ajax({
url: apiUrl+'/api/V1/Servers/UploadImage',
type: 'POST',
data: formData,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('token'));
},
cache: false,
processData: false,
contentType: false
});
});
400 error means bad request, but per my test I found it worked for me. So I'm afraid the issue in your code may relate to $('#myfile')[0].files[0], see my code below
<div>
<input type="file" id="uploadFile" />
<button id="btn4">upload</button>
</div>
$("#btn4").click(function(){
var form = new FormData();
var temp = $('#uploadFile').prop('files');
form.append("file",temp[0]);
form.append("name","myFile");
console.log(form);
$.ajax({
url: 'https://localhost:44321/hello/upload',
type: 'POST',
data: form,
cache:false,
contentType:false,//stop jquery auto convert form type to default x-www-form-urlencoded
processData:false,
success: function (d) {
alert(d)
}
});
});
public string upload(IFormFile file, string name) {
return "hello";
}

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

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")

How to upload a file using Ajax on POST?

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

Receive image in JavaScript from Java REST server sending mediaType octet stream

I am pretty new to REST and have got all the basic to work with sending JSON, but I am having problem with images. I have saved the images in a folder on my server sending a form request to my REST API in Java. Now I want to show some selected images in a in JavaScript/HTML.
My code in Java:
#Path("/getImages")
#POST
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#Consumes(MediaType.APPLICATION_JSON)
public Response getImage(int id){
File file = new File("FileLocation");
return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment;filename=\""+file.getName() + "\"")
.build();
}
I try to get it with an AJAX call:
$.ajax({
type: "POST",
url: 'url',
data: JSON.stringify(id12),
contentType: "application/json; charset=utf-8",
dataType: 'image/*',
},
success: function (response) {
//dont know what to do with the response here to get it into a <img>
},
});

Categories