What is the easiest way to submit an HTTP POST request with a multipart/form-data content type from C#? There has to be a better way than building my own request.
T
I have not tried this myself, but there seems to be a built-in way in C# for this (although not a very known one apparently...):
private static HttpClient _client = null;
private static void UploadDocument()
{
// Add test file
var httpContent = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(File.ReadAllBytes(@"File.jpg"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "File.jpg"
};
httpContent.Add(fileContent);
string requestEndpoint = "api/Post";
var response = _client.PostAsync(requestEndpoint, httpContent).Result;
if (response.IsSuccessStatusCode)
{
// ...
}
else
{
// Check response.StatusCode, response.ReasonPhrase
}
}
Try it out and let me know how it goes.
Cheers!