Last active
December 23, 2015 22:31
-
-
Save jhauge/9b061ec66858de222307 to your computer and use it in GitHub Desktop.
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
private readonly IMediaService _mediaSvc = ApplicationContext.Current.Services.MediaService; | |
// Updating profile pic | |
internal void UpdateProfilePic(int profileId, string picPath) | |
{ | |
if (profileId == 0) throw new ArgumentException("Error updating profile, no profile id in request"); | |
var contentItem = _contentSvc.GetById(profileId); | |
// Set mediaitem | |
var mediaFilename = contentItem.Name + Path.GetExtension(picPath); | |
var mediaItem = GetMediaItem(contentItem.Name); | |
using (var filestream = new FileStream(picPath, FileMode.Open)) | |
{ | |
mediaItem.SetValue("umbracoFile", mediaFilename, filestream); | |
_mediaSvc.Save(mediaItem); | |
} | |
// Update profile item | |
contentItem.SetValue("profilePic", mediaItem.Id); | |
_contentSvc.PublishWithStatus(contentItem); | |
} | |
// Gets a media item by in a named folder, creates item if it's not there | |
private IMedia GetMediaItem(string profileName) | |
{ | |
var rootFolder = _umbHelper.TypedMediaAtRoot() | |
.FirstOrDefault(m => m.Name == "Profilbilleder"); | |
if (rootFolder == null) | |
throw new ArgumentOutOfRangeException("Could not find root folder for profile pics"); | |
// Find existing item | |
var mediaContent = rootFolder.Children.FirstOrDefault(i => i.Name == profileName); | |
if (mediaContent != null) return _mediaSvc.GetById(mediaContent.Id); | |
// No mediaitem for this profile - create one | |
return _mediaSvc.CreateMedia(profileName, rootFolder.Id, "Image"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment