Greetings Reader,
I would like to quickly write a post about programmatically uploading a Image to the media library and then associating it to the contact card
Create an upload control which allows you to upload images
<asp:FileUpload ID="Img" runat="server" AssociatedControlID="Img" />
Programatically upload Media Item to Sitecore
public MediaItem AddImageToMediaLibrary() { if (!Img.HasFile) return null; var options = new Sitecore.Resources.Media.MediaCreatorOptions { AlternateText = txtName.Text, FileBased = false, IncludeExtensionInItemName = false, KeepExisting = false, Versioned = false, Destination = "/sitecore/media library/Images/Contacts/" + txtName.Text, Database = Sitecore.Configuration.Factory.GetDatabase("master") }; var filename = Server.MapPath(Img.FileName); var creator = new MediaCreator(); var mediaItem = creator.CreateFromStream(Img.PostedFile.InputStream, filename, options); PublishItem(mediaItem); return mediaItem; }
Associate the Media Item to Contact Card
if (Tracker.Current.Contact != null) { using (new SecurityDisabler()) { var image = AddImageToMediaLibrary(); MediaItem getmediaItem = Sitecore.Context.Database.GetItem(image.ID); var stream = getmediaItem.GetMediaStream(); var memoryStream = new MemoryStream(); if (stream != null) stream.CopyTo(memoryStream); var pictureFacet = Tracker.Current.Contact.GetFacet<IContactPicture>("Picture"); pictureFacet.Picture = memoryStream.ToArray(); pictureFacet.MimeType = getmediaItem.MimeType; } }
Should you have any questions, Please comment below or tweet me.
Image may be NSFW.
Clik here to view.

Clik here to view.
