Home > Net >  .NET HttpClient Image Upload to PlantNet API
.NET HttpClient Image Upload to PlantNet API

Time:07-11

I am trying to make a Request to the PlantNet API via .NET HttpClient. I have a FileStream and I am using the StreamContent and when I look via debugger at the content before it is sent it's looking good. However PlantNet response is Unsupported file type for image[0] (jpeg or png). I tried everything that came in my mind, the same request from VS Code Rest Client is working (with the same file), does anyone have any ideas if the StreamContent is messing somehow with the file data?

HttpResponseMessage responseMessage;
using (MultipartFormDataContent content = new("abcdef1234567890")) //Fixed boundary for debugging
{
  content.Add(new StringContent("flower"), "organs");

  using Stream memStream = new MemoryStream();
  await stream.CopyToAsync(memStream, cancellationToken);
  StreamContent fileContent = new(memStream);
  fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

  content.Add(fileContent, "images", fileName);

  responseMessage = await _httpClient.PostAsync(url, content, cancellationToken);
}

Note: stream is the stream of the file, in this case it comes from an ASP.NET Core API controller usingIFormFile.OpenReadStream() but I also tried opening the file directly via

new FileStream("path", FileMode.Open, FileAccess.Read)

In the Debugger content.ReadAsStringAsync() resolves to the following

--abcdef1234567890
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=organs

flower
--abcdef1234567890
Content-Type: image/jpeg
Content-Disposition: form-data; name=images; filename=test-flower.jpeg; filename*=utf-8''test-flower.jpeg


--abcdef1234567890--

which is looking absolutely fine for me, so my guess is, that somehow the file binary data may be corrupt in the content or something? When I use the above for VS Code rest client with the same file it works and I get a successful response from the PlantNet API.

(Background: I am using .NET 6 on Fedora Linux)

CodePudding user response:

Ok I solved it by removing the copy to the memory stream. This was needed as at first for debugging I opened the file directly and received exceptions if I didn't do it. The code that is working for me is

HttpResponseMessage responseMessage;
using (MultipartFormDataContent content = new("abcdef1234567890"))
{
  content.Add(new StringContent("flower"), "organs");

  StreamContent fileContent = new(stream);
  fileContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
  fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
  {
    FileName = fileName,
    Name = "images"
  };

  content.Add(fileContent, "images", fileName);

  responseMessage = await _httpClient.PostAsync(url, content, cancellationToken);
}
  • Related