NicoRiff
NicoRiff

Reputation: 4883

Sending Image by POST not sending it correctly

I have to send an image to an API that I do not control so it can do some face recognition work. It seems that I´m sending the image but I assume that it is not being done on the right way because the API response says that the image is not a JPEG file. Anyone can tell me if I´m doing it wrong??. I´m using Xamarin HttpClient Mono implementation:

MultipartFormDataContent content = new MultipartFormDataContent();
content.Headers.Add("X-Auth-Token", "eb27c17f-8bd6-4b94-bc4f-742e361b4e6a");

var imageContent = new ByteArrayContent(ultimaImagen);
content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

content.Add(imageContent, "image", "image.jpg");

try
{
    HttpResponseMessage response = await _client.PostAsync("https://10.54.66.160:9000/3/matching/search?list_id=3c9f2623-28be-435f-a49f-4dc29c186809&limit=1", content);

    string responseContent = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
    throw;
}

This is the API response:

{
    "detail": "Failed to decode image data. Detail: Not a JPEG file: starts with 0x2d 0x2d",
    "error_code": 3001
}

Upvotes: 0

Views: 590

Answers (1)

NicoRiff
NicoRiff

Reputation: 4883

Finally, I was able to discover what was causing the problem. It wasn´t neccesary to send a MultipartFormDataContent. With only the ByteArrayContent worked just fine. This is the working code:

    private async void btnVerificar_Clicked(object sender, EventArgs e)
    {
        var imageContent = new ByteArrayContent(ultimaImagen);
        imageContent.Headers.Add("X-Auth-Token", "eb27c17f-8bd6-4b94-bc4f-742e361b4e6a");
        imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

        try
        {
            HttpResponseMessage response = await _client.PostAsync("https://10.54.66.160:9000/3/matching/search?list_id=3c9f2623-28be-435f-a49f-4dc29c186809&limit=1", imageContent);

            string responseContent = await response.Content.ReadAsStringAsync();

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                await DisplayAlert("MobileAccessControl", responseContent, "OK");
            }
            else
            {
                await DisplayAlert("MobileAccessControl", "Read not OK.", "OK");
            }
        }
        catch (Exception ex)
        {
            throw;
        }
    }

Upvotes: 1

Related Questions