angular file upload converting data/payload into string - javascript

I have been using ng-file-upload to upload files to server. Recently I saw that it is converting payload/data that I am adding to it apart from file from any data type to string only. For example if I am sending integer or boolean field, it is converting it into string.
I am using django at backend, so when I print type of request data it is showing unicode and in model I have defined NullBooleanField. Because of this everytime it takes it True and save it in database as True. Below is the little snippet of what I am doing.
var _data = {'name': 'xxx',' good':false};
$scope.upload = $upload.upload({
url: URL,
method: 'PUT',
file: data_file,
data: _data,}).progress(function(evt){
});
each time when I print the type of this at backend
type(print (request.DATA['good'])))
it return
<type 'unicode'>
Am i missing something here or something is actually wrong?

Related

How to extract array data from Ajax to Python flask?

I am having problem extracting data sent from the Ajax call to the python flask backend.
I am able to extract the key:value string pair only from the request.args object. But the problem is the data I am sending is of mixed type :
e.g. data:{'data':'stringdata','Email':['abc#example.com','def#example.com'],'checkbox':'[true,true]'}
when I am reading this data from the request.args in my python module.. I am able to get request.args['data'] which returns 'stringdata' but for the other keys like request.args['Email'] I am getting BAD REQUEST errors.
I have tried JSON.stringify the data separately for each item plus the whole data object but none of it is working.
I have also tried setting the data type and the contentType in the Ajax call but still no good.
$.ajax
({
url: '/abc',
data : {
"data": 'stringdata',
"Email": ['abc#example.com','def#example.com'] ,
"Hbeat":[true,true],
"Creport" : [true,true] ,
"Treport" : [true,true] ,
"Preport" : [true,true]
},
success: function(data)
{
},
complete: function()
{
}
});
Here the python part where I am trying to get the data.:
#app.route('/abc', methods=['POST','GET'])
def checkingdata():
print(request.args)
print(request.args['data'])
print(request.args['Email']) # this is where I am getting errors.
I expect to get the data as the form they are in. e.g. where I am passing the list of emails I need to get them as list. and where there are single string values I should get them as single string values.
thanks so much for your time. Please help if you can.
You need to use request.args.getlist:
emails = request.args.getlist('Email')

JavaScript array to PHP via AJAX

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...
But what i get is something like this:
a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...
I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?
The JS code is as follows:
window.onbeforeunload = function() {
var jsonString = JSON.stringify(tabela);
$.ajax({
type: 'POST',
url: 'process.php',
data: {
text1: jsonString
}
});
}
And the PHP side is this:
$text1 = json_decode(stripslashes($_POST['text1']));
$string_data = serialize($text1);
file_put_contents("your-file.txt", $string_data);
The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize.
If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

Submit binary data via Prototype Ajax call

I'm using Prototype to submit a POST request, and the postdata contains a number of fields, one of which is binary data from a file (in this case an Excel spreadsheet the user has selected for upload.)
I am using the HTML5 FileReader interface to get the contents of the file via FileReader.readAsBinaryString() which works well. If I use charCodeAt() to print various characters in the string then they come out with the expected values.
However once I put this string data in an object (along with the other form fields) and pass it as the parameters option to Prototype's Ajax.Request(), the data arrives corrupted. Certain character values like 0x82 are replaced with 0xC2 0x82, 0xAC is replaced with 0xC2 0xAC, and so on.
I tried using window.atob() to base64 encode the string, but this fails with InvalidCharacterError: String contains an invalid character, so clearly there is some kind of processing going on which I need to avoid.
Does anyone know how to pass binary data through Prototype's Ajax.Request() while also including additional form fields in the same request?
To do ajax file upload you should really use a FormData object
var data = new FormData();
//var data = new FormData(someForm); if all your fields is in an html form
// add fields to form
data.append('fieldname',fieldvalue);
data.append('filefieldname',fileobject);
//etc
new Ajax.Request(url, {
contentType: null,
method: 'post',
postBody: data,
onSuccess: successFunction
})
With this method the server will see the request like if it was sent by a form with attribute enctype="multipart/form-data"
Doing this requires magic and pixie dust. (well not really)
firstly you would need to put the form fields values as URL parameters instead of POST and then override the post body with the file contents. For example
new Ajax.Request('/url.php?rawupload=1&id='+$F('id')+'&label='+label,
{
'method':'post',
'postBody':fileobject,
'onSuccess':function() { alert('success'); }
});
fileobject is the HTML5 file object retrieved from the file upload input element
Yes its not the most elegant solution if you have lots of form fields. You can also use Hash#toQueryString if you do have lots of form fields to build your query string instead of doing them by hand
http://api.prototypejs.org/language/Hash/prototype/toQueryString/

JS Byte Array to File on PHP Side

I have a Uint8Array which have 10000 bytes on Javascript side.
var data = new Uint8Array(10000) ;
I want to send it to PHP and create a file with it:
$.ajax({
url:'saver.php',
type: 'POST',
contentType: 'application/octet-stream',
data:data,
processData: false
});
This ajax is sending data (I see it on "Request Payload" section on console) but there is no $_POST record, $_POST array is empty, just silent. How to grab it properly?
This seems to be a known behavior.
For an array of 10000 bytes, you should be able to use
$rawPost = file_get_contents('php://input');
to get your data from the request instead of checking the $_POST variable.
Note that this method loads the data in-memory, so if the data are too large, you will get an error.
In my case.
I get binary file from JS request array : $file['content'] format of Uint8Array.
<?php
$packed = pack("c*", ...$file['content']);

Encode string javascript so that it can be transmitted to a server

I'm trying to send json string in the get request to the server, here is how it looks before encoding :
filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}
Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :
filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}
But this is how it supposed to be in order to work :
filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D
How do I get this, entirely encoded string so I can read it at server side properly ?
Reason why I used get instead of post
I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.
Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that one.
I think you're overworking this problem. Or encoding too many times. Or something.
You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.
A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.
var thing = {
groupOp : "AND",
rules : [
{ field : "countrycode", op : "eq", data : "ARG" },
...
],
...
};
var stringrep = JSON.stringify(thing);
// post via jQuery
$.ajax({
type: 'POST',
url: url,
data: stringrep,
dataType: 'json'
success: function() { ... },
});
Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.
HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.
var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));
var filtersParameter = 'filters=' + atob(JSON.stringify(filters));
Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).

Categories

Resources