Search code examples
c#web-servicesapihttp-postimage-uploading

Upload image to web API using C#


I am trying to upload an image to a web service via POST.

The API documentation says "to upload files via POST, encoded as "multipart/form-data" and include a POST arg named "image" with the image data. Images must be of type PNG, JPG, or GIF."

This is my code:

Bitmap    myImage = new Bitmap("myImage.jpg");
byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
string myBoundary = "------------------------" + DateTime.Now.Ticks;
var       newLine = Environment.NewLine;
string myContent = 
  "--" + myBoundary + newLine + 
  "content-disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine + 
  "Content-Type: image/jpeg" + newLine +
  "Content-Transfer-Encoding: binary" + newLine +
  newLine +
  Encoding.Default.GetString(myFileData) + newLine + 
  "--" + myBoundary + "--";

try {
    using (var httpClient = new HttpClient()) 
    using (var content = new StringContent(myContent, Encoding.Default, "multipart/form-data, boundary=" + myBoundary)) 
    using (var response = await httpClient.PostAsync("http://my_API_URL", content)) {
        string responseData = await response.Content.ReadAsStringAsync();
    }
}
catch (Exception myExp) { }

This code raises an exception trying to create the StringContent object.

I am ok for any suggestions. The API that I need to use requires Authentication, which typically is solved using a WebClient and this statement:

client.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("my_API_key:"));

I am OK with using any other form of POST, like WebClient or HttpClient.


Solution

  • Code that finally worked, in case anyone is looking for the same answer:

    Bitmap    myImage = new Bitmap("myImage.jpg");
    byte[] myFileData = (byte[])(new ImageConverter()).ConvertTo(myImage, typeof(byte[]));
    string myBoundary = "---------------------------7df3c13714f0ffc";
    var       newLine = Environment.NewLine;
    string  myContent =
      "--" + myBoundary + newLine + 
      "Content-Disposition: form-data; name=\"image\"; filename=\"myImage.jpg\"" + newLine +
      "Content-Type: image/jpeg" + newLine +
      newLine +
      Encoding.Default.GetString(myFileData) + newLine +
      "--" + myBoundary + "--";
    
    using (var client = new WebClient()) {
        try {
            client.Headers["Authorization"] = "Basic xxxxxx";
            client.Headers["Content-Type"]  = "multipart/form-data; boundary=" + myBoundary;
            client.UploadString(new Uri(myURL), "POST", myContent);
            totalAPICalls++;
        }
        catch { }
    }