【问题标题】:Sending Image by POST not sending it correctly通过 POST 发送图像未正确发送
【发布时间】:2018-01-26 13:31:38
【问题描述】:

我必须将图像发送到我无法控制的 API,以便它可以进行一些人脸识别工作。似乎我正在发送图像,但我认为它没有以正确的方式完成,因为 API 响应说图像不是 JPEG 文件。任何人都可以告诉我我是否做错了???我正在使用 Xamarin HttpClient Mono 实现:

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

这是 API 响应:

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

【问题讨论】:

  • 如何获取字节数据?您是否尝试将 imageContent 转换回 jpeg?
  • @DogeAmazed 我通过转换从相机获得的数据来获得字节数据。我认为我正在做的请求并不完全正确。
  • @NicoRiff 你能通过 Postman 成功地 Post 到你的 web api 吗?如果是这样,请将 Postman 代码 sn-p 添加到您的问题中
  • @NicoRiff 我会检查您的字节数组的 JPEG 标头是否正确:en.wikipedia.org/wiki/JPEG#Syntax_and_structure
  • 或许你应该发送base64格式的图片?这取决于api服务

标签: c# xamarin xamarin.forms mono dotnet-httpclient


【解决方案1】:

最后,我能够发现导致问题的原因。无需发送MultipartFormDataContent。只有ByteArrayContent 工作得很好。这是工作代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 2012-11-14
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2010-10-16
    相关资源
    最近更新 更多