You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Xamarin HttpClient POST图片至人脸识别API报错:非JPEG文件

Fixing JPEG Upload Issue with Third-Party Face Recognition API

Let's break down what's causing this error and fix it step by step.

First, let's look at the error message you got:

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

The 0x2d hex value translates to the - character. That means the API is receiving the multipart form's boundary separator (--xxxxxx) instead of actual JPEG data. Here's why that's happening in your code:

Key Mistakes in Your Implementation

  • You're setting the ContentType of the entire MultipartFormDataContent to image/jpeg, which is wrong. MultipartFormDataContent needs to use the multipart/form-data content type (with an auto-generated boundary) so the API knows to parse it as a form with multiple parts.
  • You didn't set the ContentType for the image content itself—that's where the image/jpeg header belongs.

Corrected Code

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

var imageContent = new ByteArrayContent(ultimaImagen);
// Assign the image/jpeg content type to the image data, not the entire form
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
// Add the image part to the multipart form
content.Add(imageContent, "image", "image.jpg");

try {
    // Fix the URL: replace & with & (HTML entity encoding isn't needed here)
    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();
    // Add your response handling logic here
} catch (Exception ex) {
    throw;
}

Why This Works

  1. Let MultipartFormDataContent handle its own content type: When you create a MultipartFormDataContent, it automatically generates a unique boundary string and sets the correct Content-Type: multipart/form-data; boundary=xxxxxx header. Overwriting this with image/jpeg confuses the API into treating the entire form payload as a single image file.
  2. Set the image content type correctly: By adding image/jpeg to the ByteArrayContent that holds your image data, you tell the API exactly what type of content is in that form part.
  3. Fix the URL encoding: The & in your URL is HTML entity encoding for &—HttpClient doesn't need this, so replacing it with a plain & ensures the query parameters are parsed correctly.

内容的提问来源于stack exchange,提问作者NicoRiff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:29:02