Last active
March 19, 2016 12:50
-
-
Save danbarua/7664d4b7bf77286ff832 to your computer and use it in GitHub Desktop.
Upload file with form data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var content = new MultipartFormDataContent()) | |
{ | |
//hackety hack hack hack | |
//this will throw if object has complex/nested properties | |
var messageAsKeyValuePairs = JsonConvert.DeserializeObject<IDictionary<string, string>>(JsonConvert.SerializeObject(message)); | |
foreach (var kvp in messageAsKeyValuePairs.Where(kvp => kvp.Value != null)) | |
{ | |
content.Add(new StringContent(kvp.Value), kvp.Key); | |
} | |
var streamContent = new StreamContent(source); | |
streamContent.Headers.Clear(); | |
streamContent.Headers.Add("Content-Type", "application/octet-stream"); | |
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + fileName + "\""); | |
content.Add(streamContent, "file", fileName); | |
var response = await client.PostAsync(requestUrl, content); | |
return await response.Content.ReadAsAsync<TReturn>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment