From client side A, I want to create a file on the fly by javascript and send it to a Django server B via Ajax for further processing.
The javascript code in A is like below. I use blob to create a file without a real uploaded one and send it via Ajax.
console.log("start sending binary data...");
var form = new FormData();
var blob = new Blob([bytesArray], {type: 'example/binary'});
form.append('file_name', blob, 'test.bin');
$.ajax({
url: THIRD_SERVER + 'test_binary',
type: 'POST',
data: form,
processData: false,
success: function(data){
console.log('test_binary ' + JSON.stringify(data));
}
});
However, on the Django server, what I got is like this (when i print request.POST), hence when i used Django FileUpload, it returned an exception.
<QueryDict: {u' name': [u'"file_name"'], u'------WebKitFormBoundarybCp3z7mAduz8BBDq\r\nContent-Disposition: form-data': [u''], u' filename': [u'"test.bin"\r\nContent-Type: example/binary\r\n\r\n\ufffd\ufffd\ufffd\x01\x05\x06\r\n------WebKitFormBoundarybCp3z7mAduz8BBDq--\r\n']}>
So I guess the above javascript doesn't do the right thing to send file to a Django server. Is there any proper way that I can use the FileUpload to handle?
Thanks,
You have to tell $.ajax not to set a content type otherwise it will be set incorrectly
$.ajax({
url: THIRD_SERVER + 'test_binary',
type: 'POST',
data: form,
processData: false,
contentType: false,
success: function(data){
console.log('test_binary ' + JSON.stringify(data));
}
});
Related
I'm using ajax to send file via POST request to the server (my Flask app), but I can only retrieve this file (binary data) in Flask using request.form, not request.files, and request.files is desired. Code as below.
How can I get file with request.files ? (Conversely, with Postman and other tools, I can get the file with request.files. In request.form case, info such as content-type is missing)
// "file_content" is read previously
var formData = new FormData();
formData.append("file", file_content); // "file_content" is binary data
.ajax({
type:"POST",
async: false,
url: ...,
data: formData,
dataType:"json",
processData: false,
contentType: false,
});
The tricky thing is send a local file, and most relevant answers are using document.getElementById().
I'm trying to use the google chart api in an XPages application.
I'm using the code example given by the documentation : https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file
I have to replace the call to the php page by a call to an LS agent.
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
So my code goes to :
var jsonData = $.ajax({
url: "http://server/database/agent?openagent",
dataType: "json",
async: false
}).responseText;
On my local domino server, it works fine.
On the production domino server, I get nothing. The chart is not drawn. After debugging the js client side, it seems the ajax call is expecting an authentification even if I had to log in before.
The anonymous access is not allowed on both servers.
The security level seems to be same on both environments
Any help will be welcome (or any other way to proceed if I'm wrong).
Thank you
If you are able to draw the google chart in your local server, but not in production server, this means it is your server issue.
You can add authentication header in your jquery ajax call to make authenticated ajax request
$.ajax({
headers: {
"Authorization": "Bearer <TOKEN HERE>"
}
})
You can also send username and password in jquery ajax call, to make authenticated request. Here is the sample code from the link
$.ajax({
type: 'GET',
url: 'url',
dataType: 'json',
//whatever you need
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth(user, password));
},
success: function () {});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
at the end, I tried to run the ajax request through dojo instead of Jquery.
My codes became this one :
var jsonData = dojo.xhrGet({
url: "http://server/database/agent?openagent",
handleAs:"json",
...
})
I did no changes at the security level or anything else.
I do not understand why the jquery syntax is not working as well the dojo syntax.
anyway, it is working now.
Many thanks to all for your suggestions
I wanted to retrieve data using ajax, when open the url in browser it showing data but when i execute this url in ajax code error msg function is running however data is showing in browser.
url: "http://live.nayatel.com/?json=1"
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://live.nayatel.com/?json=1",
cache: false,
success: onSuccess,
error: onError
});
});
its a wordpress site and i used a plugin to retrive its data working in browser but not giving response text.
I have two suggestions, since I am not that sure about your problem.
a) Try changing
success: onSuccess,
to
success: function(data, status) {
onSuccess(data, status);
},
b) If that fails, try adding
crossDomain: true,
I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.
I have form where I use ajax way to upload images and like to send the uploaded images to back to form to hidden fields. How to do that? I am trying the uploaded images to be send to hidden field. like this, document.getElementById("hid").value = res;
I use the ajax code like this,
if (formdata) {
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
document.getElementById("hid").value = res;
}
});
}