0

I need to send to Web Service a POST request with body that is represented as "multipart/form-data" Content-type.

The sample of the body is the following:

Content-Type:multipart/form-data; boundary=WebBoundary

--WebBoundary
Content-Disposition: form-data; name="Key#1"
Value#1

--WebBoundary
Content-Disposition: form-data; name="Key#2"
Value#2

--WebBoundary
Content-Disposition: form-data; name="FileKey"; filename="file.jpg"
Content-Type: image/png

--WebBoundary--

How can I construct MIME message for this use case using HttpWebRequest? I want also to customize data I send. For example at first I send 3 keys where 2 keys are strings and one is image, and other time I want to send 5 keys of image type. Anyway I didn't find in .NET library how to do it.

If anyone has a solution for this, I'll appreciate it.

Thank you in advance.

Dragon
  • 2,431
  • 11
  • 42
  • 68
  • At the end I had to make my own solution. And the following article helped me with this: http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx – Dragon May 24 '12 at 15:20

1 Answers1

0

Any one arriving at this, 9 years later and in the era of .NET Core 3.11 and higher, you can achieve what the original poster wanted using the following C# code:

namespace UploadTester
{
  class Program
  {
    static async Task Main(string[] args)
    {
      var client = new HttpClient();

      Stream fileStream = new FileStream("P:\\testytesty\\test1.pdf", FileMode.Open);

      var FormData = new MultipartFormDataContent();

      var payloadData = new Dictionary<string, string>();
      payloadData.Add("AttachmentKey", "4567");
      payloadData.Add("FileName", "test1.pdf");
      payloadData.Add("Notes", String.Empty);
      payloadData.Add("UploadedBy", "UploadPerson");
      payloadData.Add("UploadDate", DateTime.UtcNow.ToShortDateString());
      payloadData.Add("Compressed", "false");
      payloadData.Add("DocType", "1");

      foreach(var payloadItem in payloadData)
      {
        FormData.Add(new StringContent(payloadItem.Value), payloadItem.Key);
      }

      FormData.Add(new StreamContent(fileStream), "AttachmentFile", "test1.pdf");

      var request = new HttpRequestMessage(HttpMethod.Post, "http://The-url-of your-post/accepter/goes-here");

      request.Headers.Add("accept", "application/json");

      request.Content = FormData;

      var response = await client.SendAsync(request);



    }
  }
}

It's as a console mode program for me, because that's what I was using to test my API, rather than having to fire up the entire client app every time.

But it should be easy enough to extract the core out of it, and insert it into a method in a class.

I've not yet worked out how to set the mime type for the file being uploaded however, but if you review this request in progress, using a web debugger such as fiddler, you'll see it follows the exact format the OP wanted.

shawty
  • 5,729
  • 2
  • 37
  • 71