Handle binary data at backend using golang - go

I don't even know if i had asked the right question or not, but here it go anw.
The question is which data type in golang i should use to store binary data
In the front end i using vuejs and sending a file with axios post request using formData as request body.
1 field in this body is a file which if i check in the devtool it show as (binary) like this : enter image description here
and if i console log it's type then it show as an object
In the front end i send the request :
CreateAccount(){
var formData = new FormData();
formData.append('cv',this.cv);
axios({
method : 'post',
url : 'http://localhost:1323/restricted/Profile',
headers: {
'Authorization' : 'Bearer ' + this.$store.state.token,
'Content-Type': `multipart/form-data;`,
},
data : formData})
In the backend with golang, i use []byte to store this data like this :
Cv []byte `json:"cv" form:"cv" query:"cv"`
But this field return as an empty array, maybe there is a missmatch data type in here so they just don't store my data ?? please help. I have struggle with this 1 task(sending a file in the front end and receive that file in the backend, store it in the postgre db) for more than 3 days
Ther are actually no error. It just that mine Cv varible in the backend return empty, there are nothing in it whereas the other field had the correct value

Related

Malformed request from aiohttp.ClientSession().post() with multiple image files

I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file

Include date field in to the header requests Web Api

Is it possible to enable date field in to http requests? I have an object on my client side:
let init = {
method: typeof method === 'string' ? method : 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
'Accept-Language': getLanguage()
}
The problem is I adding 'Date' : new Date() to the header server doesn't get any key-value pair (via WebApi). Also in network section of browser there is no above field. I've read some information this field is closed for any manipulation. As I understand I need to enable it for including not by hands. So, how can I tell to browser to send it?
Unfortunately, that's not possible once the browser is supposed to set the header, not you. If you were able to set the header, that would defeat the purpose of the security feature.
Also, if you try to force it you'll probably get the error:
Refused to set unsafe header "Date"
Once we try the request without setting this header, we'll see that the browser doesn't set it for you (only for response object, which is easier to manipulate).
Some alternatives:
Create custom headers and receive their values at the WebApi
Or even pass the value as a parameter (body POST, e.g)

Sending JSON List Of Object to Spring MVC controller

I have an issue with sending a List Of Objects to Spring MVC controller .
The list of object is like this
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
And I send the above data with the following AJAX code:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : JSON.stringify(adresses.toArray()),
});
When I use this form of ajax, it worked for me and the format sended is as follow:
Request Payload :
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
Yes, even the above one is worked, when i send it like as follow:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : {adresseList : JSON.stringify(adresses.toArray())},
});
It doesn;t work for me. The sending data is look like
listAdresse=%5B%7B%22alias%22%3A%221%22%2C%22rue%22%3A%22Rue+de+la+Senette%22%2C%22codePostal%22%3A%2278955%22%2C%22ville%22%3A%22Carri%C3%A8res-sous-Poissy%22%2C%22rueComplement%22%3A%22%22%7D%5D
Response Headersview source
And, It gave an error: 400 bad request
Here, my controller
#RequestMapping(value = "creerlivraison/ajouterclientBD",method=RequestMethod.POST)
public String ajouterClientBD(#RequestBody Adresse[] listAdresse, Principal principal) {
for (Adresse adresse : listAdresse) {
System.out.println(adresse);
}
return "ok";
}
I want to know that "What is the difference between the two ajax request?", why the request payload is formatted when I wrap the data inside the braquets {} and specify listAddress.
Here is screen capture:
http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
In this instance,
JSON.stringify(adresses.toArray()) is string, just keep the JSON format.
{adresseList : JSON.stringify(adresses.toArray())} is an object, so it is converted to a query string.

Query Ajax and REST HTTP Basic

i was reading an article on Query Ajax and REST HTTP Basic and here i got this http://blog.rassemblr.com/2011/05/jquery-ajax-and-rest-http-basic-authentication-done-deal/
just see the code
$.ajax( {
url : '/model/user.json',
dataType : 'json',
beforeSend : function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authorization", "Basic " + base64);
},
error : function(xhr, ajaxOptions, thrownError) {
reset();
onError('Invalid username or password. Please try again.');
$('#loginform #user_login').focus();
},
success : function(model) {
cookies();
...
}
});
i just do not understand what kind of file type is user.json. please anyone who is familiar with .json file type then please tell me what kind of file type it is. thanks
Its not a file in this case. It is RESTful URL, .json part just asks server to return results in JSON format. Probably you can use /model/user.xml to get response in XML format. Twitter and many other services does this the same way.
Another common way to request specific response format is by providing HTTP Accept header.
For further reading I recommend this resource: http://blog.2partsmagic.com/restful-uri-design
Some applications return different data if the user adds a different
extension. e.g. they may ask for contacts.xml or contacts.json. But
different URIs imply different resources. Are the two data formats
really two different resources? Or just two different representations
of the same resource.

Making jQuery $.ajax call to Twitter API 1.1 search

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`

Resources