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

[code language=”csharp”]
<asp:FileUpload ID="Img" runat="server" AssociatedControlID="Img" />
[/code]

Programatically upload Media Item to Sitecore

[code language=”csharp”]
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;
}
[/code]

Associate the Media Item to Contact Card

[code language=”csharp”]
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;
}
}
[/code]

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

Powered by WordPress.com.

Up ↑

%d bloggers like this: