Skip to content

Instantly share code, notes, and snippets.

@beckettkev
Last active August 29, 2015 14:21
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 beckettkev/6fc003d4305778d9dad5 to your computer and use it in GitHub Desktop.
Save beckettkev/6fc003d4305778d9dad5 to your computer and use it in GitHub Desktop.
/// <summary>
/// Gets a local Base64 string of the remote Image (14)
/// e.g. /api/values?url=/sites/sitecollection/subweb/PictureOfTheThames.jpg
/// </summary>
/// <param name="path">Relative Site Path to the Image</param>
/// <returns>Base64 string of the remote Image</returns>
public async Task<string> Get([FromUri] string path)
{
string webAPIEndpoint = String.Format("{0}/_api/web/GetFileByServerRelativeUrl('{1}')/$Value", webAPIResourceID, path.Substring((path.ToLower().IndexOf("/sites"))));
string type = path.Substring((path.LastIndexOf('.') + 1));
try
{
/*
GET THE AUTH HEADER HERE...
As detailed here...
http://blogs.msdn.com/b/kaevans/archive/2014/04/15/calling-o365-apis-from-your-web-api-on-behalf-of-a-user.aspx
*/
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, webAPIEndpoint);
request.Headers.TryAddWithoutValidation("Authorization", authResult.CreateAuthorizationHeader());
var response = await client.SendAsync(request);
var imgBytes = await response.Content.ReadAsByteArrayAsync();
string img = Convert.ToBase64String(imgBytes);
//data types and content types like 'JPEG' and not 'JPG'
return String.Format("data:image/{0};base64,{1}", type, img).Replace("jpg","jpeg");
}
catch (Exception oops)
{
throw oops;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment