I have a problem on my code. I want to upload the image file by using formdata and ajax to the server side python program. But I got django.utils.datastructures.MultiValueDictKeyError: "'image'" error in my server uwsgi.log. I think it may not upload the image file to the server, but I don't understand what is wrong on my code.
My client code is the following.
function imageFileUploader(imageType, image) {
var credentials = {
filetype: imageType,
};
var image_file = image;
$.ajax({
url: HOST_NAME + "user/api/get_filename/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// Test if the image is shown -> success
document.getElementById("previewimage").src = image
var formData = new FormData();
formData.append('filename', image_file_name);
formData.append('image', image);
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST',
timeout: 10000,
data: formData,
processData: false,
contentType: false,
})
.done(function (data) {
jsondata = JSON.parse(data);
alert("File upload completed...");
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
})
}
function snapPicture () {
navigator.camera.getPicture (onSuccess, onFail,
{quality: 50, destinationType: Camera.DestinationType.FILE_URI,
saveToPhotoAlbum: true});
function onSuccess (imageURI) {
var file_name = imageFileUploader("T", imageURI);
if (file_name == "") {
console.log("False");
}
else {
image_send(file_name);
}
}
function onFail (message) {
console.log("False");
}
}
And my server side code is the following.
def post(self, request, format=None):
outputLogFile("Upload Function is called...")
req_file_name = request.data['filename']
req_image = request.FILES['image']
I can get filename from the client when I comment the code of image. Please give me an advice.
Related
I am sending file along with some data to backend which is written by flask. the backend is handling the request successfully but the ajax is not handling the response from the backend. Here my jquery code
$(document).ready(function () {
$("#upload").click(function () {
const title = $("#tutorial-title").val();
const description = $("#tutorial-description").val();
const file = $("#tutorial-file").prop("files")[0];
const selectedOption = $("#course option:selected").val();
const formData = new FormData();
formData.append("title", title);
formData.append("description", description);
formData.append("file", file);
formData.append("category", selectedOption);
$.ajax({
url: "http://127.0.0.1:5000/api/v1/create",
type: "POST",
data: formData,
contentType: false,
processData: false,
})
.done(function (response) {
alert("Thank You!");
window.location.replace("home.html");
$("#form1").reset();
})
.fail(function (error) {
console.error(error);
alert("error");
});
});
});
The backend is responding as it supposed to. Here are responses from backend.
127.0.0.1 - - [05/Jan/2023 12:00:05] "POST /api/v1/create HTTP/1.1" 500 -
127.0.0.1 - - [05/Jan/2023 12:00:49] "POST /api/v1/create HTTP/1.1" 201 -
I don't know where to go from here now.
$(document).ready(function () {
$.ajax({
statusCode: {
201: function() {
alert('201 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
},
url: "http://127.0.0.1:5000/api/v1/create",
type: "POST",
contentType: false,
processData: false,
})
.done(function (response) {
console.error(response);
})
.fail(function (error, textStatus, code) {
switch (code) {
case 404:
// Take action,
//referencing textStatus as needed.
default:
console.log('Sorry, error');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
one of the possible solutions
So I have this function that gets the user details via UUID;
function getUserDetails(uuid){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
console.log(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
which give me the result of
AJAX RESULT
Now I wonder how to access that data. The function is from different js page. How can I throw the json result to another js page?
Im using JQUERY. Thanks and more powers.
When you use ajax it takes some time to return the data form server to client, so you can use promise or callbacks:
Callbacks:
function.js
function getUserDetails(uuid, callback){
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
callback(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
}
});
}
index.js
getUserDetails(uuid, function(data){
console.log(data);
});
Promises
function.js
function getUserDetails(uuid){
return new Promise((resolve, reject) => {
$.ajax({
url:'http://localhost/hrms/controller/php/getUserDetails.php',
method: 'POST',
dataType: 'json',
data: { uuid: uuid },
success:function(result){
resolve(result);
},
error: function(xhr, status, error){
if(xhr.status == 401){
toastr.error(xhr.responseText);
}
const reason = new Error('Error');
reject(reason);
}
});
});
}
index.js
getUserDetails(uuid).then(function(data){
console.log(data);
});
I try send a binary file with jquery to node js.
This is my jquery code:
$('#addLabel').click(function(){
$.ajax({
url: "http://127.0.0.1:3030/label/66806",
type: 'PUT',
data: files,
contentType: 'application/octet-stream',
dataType: 'binary',
contentType: false,
processData: false,
success: function (data) {
console.log("sent file");
},
error: function (xhr, status, error) {
console.log("error " + status + " " + error);
}
});
});
var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event)
{
files = event.target.files;
}
For example I need only show in console a data like below:
update(id, data, params) {
console.log(data);
return Promise.resolve(data);
}
Firebug show me that a data was sent but node show me only {}. Sent data are empty. What is wrong?
Jeez... How about that title, terrible lol.
Well I am using jquery-comments by Viima. (http://viima.github.io/jquery-comments/)
I'm trying to use ajax commands to a Node.JS script that will update a JSON file. All of which is local, no crossing domains or anything.
Here is my Node.JS script:
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.writeFile("/comments-data.json", "commentJSON", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
Here is the Ajax post
postComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://127.0.0.1:8080',
data: commentJSON,
success: function(comment) {
success(comment)
},
error: error
});
},
I don't want to redirect. I just wanted to asynchronously show the new comment. Also this script will ultimately have to be able to handle video attachments as well and store the filepath inside the JSON file. But i believe, Jquery-comments just reads the file path from the JSON
Here is what the support site says for attachments
uploadAttachments: function(commentArray, success, error) {
var responses = 0;
var successfulUploads = [];
var serverResponded = function() {
responses++;
// Check if all requests have finished
if(responses == commentArray.length) {
// Case: all failed
if(successfulUploads.length == 0) {
error();
// Case: some succeeded
} else {
success(successfulUploads)
}
}
}
$(commentArray).each(function(index, commentJSON) {
// Create form data
var formData = new FormData();
$(Object.keys(commentJSON)).each(function(index, key) {
var value = commentJSON[key];
if(value) formData.append(key, value);
});
$.ajax({
url: '/api/comments/',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(commentJSON) {
successfulUploads.push(commentJSON);
serverResponded();
},
error: function(data) {
serverResponded();
},
});
});
}
});
This is my server side code
var response = new HttpResponseMessage
{
Content = new StringContent("FAIL FAIL"),
StatusCode = HttpStatusCode.InternalServerError,
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
return Task<HttpResponseMessage>.Factory.StartNew(() => response);
This is my client side code using jquery
$.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
console.log(data);
},
error: function (jqxhr) {
console.log(jqxhr);
}
});
But when I check using firebug, my jqxhr.responseText is "".
How do I retrieve "FAIL FAIL"?
Try like this:
var ajaxReult = $.ajax({
type: 'POST',
url: 'someurl',
data: somevalues,
success: function (data) {
// console.log(data);
},
error: function (jqxhr) {
// console.log(jqxhr);
}
}).responseText;
console.log(ajaxReult);