Uploading a Photo as Multipart Form Data in C#

I recently posted about adding a feature to a Windows 8 app I’m working on wherein the user can select a photo from their pictures library. After they select the photo, I need to upload it to the API I’m using in order to post the picture. The API specifies:

POST /api/media</code> [multipart] AUTHENTICATED

Multipart POST parameters:
  • caption — The caption text.
  • media — The file body itself.

This means that I need to perform an (authenticated) multipart form POST to their API with the image body as a parameter called “media” and an optional caption for the image. However, there were a few issues that I ran into: 1. One missing specification and 2. An issue with default naming of HTTPContent added to a MultipartFormDataContent object in C#.

First, I had to build up the MultipartFormDataContent, assuming that photoContents is a Stream from the file chosen by the user.

If you notice that I explicitly add (escaped) quotation marks to the names of the content objects I’m adding to the MultipartFormDataContent. This was the second from above. When I didn’t explicitly add the quotation marks, the request generated had a ContentDisposition like this (from Fiddler):

Content-Disposition: form-data; name=media; filename=picture.jpg

versus:

Content-Disposition: form-data; name="media"; filename="picture.jpg"

I’m not sure if this is a standard or not. I was able to find that the quotations around the boundary parameter of Multipart request are optional according to my test, but required if the boundary starts with two dashes. I couldn't find an RFC reference supporting that the quotes around the boundary are optional. The quotes around the parameter’s names may or may not be optional. In any case, when I added them to my request, it succeeded.

As a side note, the “filename” attribute you see was necessary for the request to succeed in the API I’m using, but was not specified in the documentation. This was the first issue above.

In the snippet above, I call PostBuffer(uri, content) which is a helper function to most the MultipartFormDataContent. Here’s what it does, to post the content: