Tuesday, December 12, 2006

Uploading media items from the front end


Why not? What if you want the extranet users to upload media to the master database? No problem with that! Just follow these easy steps to accomplish this.

Step 1: add a new pipeline to the <processors> section in the web.config:

<frontendUpload>

<processor mode="on" type="Sitecore.Pipelines.Upload.Save, Sitecore.Kernel" />

</frontendUpload>

Step 2: Add the FileUpload control to your layout (web form):

<asp:FileUpload ID="FileUpload1" runat="server" />

This control will be used to select a image for uploading.

Step3: in the code behind of a layout you should add the following code for example in the button click handler.

// defining if a file is being uploaded

if (FileUpload1.PostedFile != null)

{

// disabling security in order to create a media item

using (new Sitecore.SecurityModel.SecurityDisabler())

{

// creating necessary arguments to be passed to the processor

UploadArgs args = new UploadArgs();

// adding http files collection

args.Files = base.Request.Files;

// a media path where the media item will be created

args.Folder = "/sitecore/media library/Files";

// we may want to override existing media items

args.Overwrite = true;

// we do not need to choose this option since we are uploading images, not archives

args.Unpack = false;

// turning on versioning for the uploaded item

args.Versioned = true;

// selecting a language in which the media item will be created

args.Language = Sitecore.Globalization.Language.Parse("en");

// we are uploading to the database

args.Destination = UploadDestination.Database;

// if we are uploading to the master database, we need to change the active site

Sitecore.Context.SetActiveSite("shell");

// starting the pipeline previously added to web.config

PipelineFactory.GetPipeline("frontendUpload").Start(args);

// the media item is created. Now we can do whatever we want with the uploaded items

// for exampe, programmatically populate the Alt fields

foreach (Item itm in args.UploadedItems)

{

itm.Editing.BeginEdit();

itm.Fields["Alt"].Value = "Set from API";

itm.Editing.EndEdit();

}

// setting the active site back

Sitecore.Context.SetActiveSite("website");

}

}

else

{

Response.Write("No file is posted.");

}

3 comments:

Unknown said...

Nice example!

P.

Anonymous said...

It stopped working when we migrated to Sitecore 6.6

Anonymous said...

Alex: we were using this code for more than a year with sitecore 6.4. Now after a migration to sitecore 6.6 we are getting the dreaded error "Empty strings are not allowed.
Parameter name: name" on pp.start(args) statement. Not sure about what's causing the error.