Sitecore 8 : Programatically Upload and Associate Image to Contact Card

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);
            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.

One thought on “Sitecore 8 : Programatically Upload and Associate Image to Contact Card

Add yours

  1. Does Sitecore 8 not provide any interface for editing contacts? You would think that if they put these default fields in the Contact tables, they would also provide a default way to actually edit them.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at

Up ↑

%d bloggers like this: