Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Last active January 12, 2016 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/4effc428efe4868c922a to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/4effc428efe4868c922a to your computer and use it in GitHub Desktop.
HttpClient Extension Method to send image byte[] data to API
public static class HttpClientExtensions
{
/// <summary>
/// Helper method to POST binary image data to an API endpoint that expects the data to be accompanied by a parameter
/// </summary>
/// <param name="client">HttpClient instance</param>
/// <param name="imageFile">Valie StorageFile of the image</param>
/// <param name="apiUrl">The API's http or https endpoint</param>
/// <param name="parameterName">The name of the parameter the API expects the image data in</param>
/// <returns></returns>
public static async Task<HttpResponseMessage> PostImageDataAsync(this HttpClient client, StorageFile imageFile, string apiUrl, string parameterName)
{
if (client == null)
throw new ArgumentNullException(nameof(client), "HttpClient was null");
if (string.IsNullOrEmpty(apiUrl))
throw new ArgumentNullException(nameof(apiUrl), "You must set a URL for the API endpoint");
if (imageFile == null)
throw new ArgumentNullException(nameof(imageFile), "You must have a valid StorageFile for this method to work");
if (string.IsNullOrEmpty(parameterName))
throw new ArgumentNullException(nameof(parameterName), "You must set a parameter name for the image data");
try
{
byte[] fileBytes = null;
using (var fileStream = await imageFile.OpenStreamForReadAsync())
{
var binaryReader = new BinaryReader(fileStream);
fileBytes = binaryReader.ReadBytes((int)fileStream.Length);
}
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(fileBytes), parameterName);
return await client.PostAsync(new Uri(apiUrl), multipartContent);
}
catch (Exception ex)
{
throw ex; //do whatever make sense in your app (ie. log it, show it to the user, etc.)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment