Receive file with request.files vs request.form in Flask - ajax

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().

Related

FormData object is empty in asp.net mvc5 controller when ie11 browser is used to send request data

Currently my application logic works correctly on Chrome and Firefox browser, but for some reason it doesn't work in the same way on IE11 browser. I have following function which is called from related with it html button :
function sendStatus(url, status, comment) {
var formData = new FormData();
formData.append('status', status);
formData.append('comment', comment);
$.ajax({
method: "POST",
url: url,
contentType: false,
data: formData,
processData: false,
cache: false,
error: showErrorMessage,
success: showPreview
});
and if request are coming to server from IE11, then HttpContext.Request.Form property doesn't include anything placed into formData. The same request called from Chrome/Firefox include everything declare in formdata object. Is there anything that I need to change in that code or provide some additional logic for ie11 browser ?

Can't figure out how to read the data passed in from form data

having trouble accessing a file I'm sending over in a formData object into node. Code in coffeescript. Sending:
formData = new FormData()
formData.append("upload", file)
$.ajax
url: "/onboard/groups/csv"
method: "POST"
dataType: "json"
cache: false
data: formData
contentType: false
processData: false
success: (data) ->
console.log "OStore post-processed data: ", data
callback(null, data)
Receiving:
router.post "/onboard/groups/csv", (req, res, next) ->
file = req.files?['upload']?
fs.readFile file, (err,data) ->
console.log err if err
return file = data
console.log "postfile: ", file
Not very experienced with fs but should I be doing something differently to access the file? use path? thanks for any help.
You are going to want to use something like https://github.com/mscdex/connect-busboy.
The file being uploaded is in the request, but is not yet on the filesystem it is in the memory of the server. So, we can not read it from the file system and need to read it from the request.
Something like busboy, or any other streaming parser library for Node will help you accomplish this!

Submitting files to django server from outside via Ajax

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

phonegap : POST data not being received on the server

I am building iOS app in Phonegap and trying to do an ajax POST call to remote server. Server gets the call. It responds fine, but the server doesn't seem to get any of the POST data.
Ajax call is as follows :
var formData = $(this).serialize();
$.ajax({
type:'post',
url:'https://www.mySite.com/ajax/test',
data: formData,
dataType: "json",
crossDomain:true,
async: true,
success: function (result) {
alert(result.success)
},
error: function (request,error) {
alert('error');
}
});
On the server (for testing purposes), I'm just bringing it back
$json = array('success' => 'true'.serialize($_POST));
I print the $_POST variable on the server. Whenever the iPhone gets the callback, all the POST data is missing. The variable formData definitely has the information. I'm confused whether it actually sends it or the server strips it away.
Any help is greatly appreciated.

wcf service json 400 Bad Request

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.

Resources