使用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
ContentTypeof the entireMultipartFormDataContenttoimage/jpeg, which is wrong.MultipartFormDataContentneeds to use themultipart/form-datacontent type (with an auto-generated boundary) so the API knows to parse it as a form with multiple parts. - You didn't set the
ContentTypefor the image content itself—that's where theimage/jpegheader 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
- Let
MultipartFormDataContenthandle its own content type: When you create aMultipartFormDataContent, it automatically generates a unique boundary string and sets the correctContent-Type: multipart/form-data; boundary=xxxxxxheader. Overwriting this withimage/jpegconfuses the API into treating the entire form payload as a single image file. - Set the image content type correctly: By adding
image/jpegto theByteArrayContentthat holds your image data, you tell the API exactly what type of content is in that form part. - 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
相关产品推荐
相关产品推荐

