zapoo zapoo - 9 months ago 74
reST (reStructuredText) Question

Face API Base64 image post returns badrequest

Face API works with URL of the image but when I try to send image as
Base64 encoded it returns an error.
In this sample code I used Restsharp to send the data

My code is like below.

public string GenerateRest(String Base64Image)
var serviceURL = Constants.BaseServiceURI;
var client = new RestClient(serviceURL);

var request = new RestRequest(Constants.BaseResoruce, Method.POST);
request.AddHeader("Ocp-Apim-Subscription-Key", Constants.MS_API_KEY);
request.AddHeader("Content-Type", "application/octet-stream");

request.RequestFormat = DataFormat.Json;

var baseString = Base64Image.Replace("data:image/jpeg;base64,", String.Empty);

byte[] newBytes = Convert.FromBase64String(baseString);

// execute the request
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string

return content;

Answer Source

Restsharp looks a bit idiosyncratic when taking a binary payload. Instead of request.AddBody, which adds a multipart form section, you need to do the following:

request.AddParameter("application/octet-stream", newBytes, ParameterType.RequestBody);

c.f. Can RestSharp send binary data without using a multipart content type?