Stream Sitecore media items to HttpResponse

Here is a small tip for you who is doing API’s based on Sitecore. How to get an item from the Sitecore Media Library and stream it to the HttpResponse of a page.

This is an example of an .ashx HttpHandler class that gets the ID of an Sitecore Media Library item and streams the item. Add your own exception handling as you wish.

using System;
using System.Net;
using System.Web;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Configuration;

namespace MyProject
{
  public class GetImage : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      // ID of media item
      string id = context.Request.QueryString["id"];

      // Get media item
      MediaItem item = (MediaItem)Factory.GetDatabase("web").GetItem(id);

      // Get name to be shown when image is saved
      string imageName = item.Name + "." + item.Extension;

      context.Response.Clear();
      context.Response.ContentType = mediaItem.MimeType;
      context.Response.AppendHeader("Content-Disposition", string.Format("inline;filename=\"{0}\"", imageName));
      context.Response.StatusCode = (int)HttpStatusCode.OK;
      context.Response.BufferOutput = true;
      // Copy the media stream to the response output stream
      mediaItem.GetMediaStream().CopyTo(context.Response.OutputStream);
      // As momma always said: Always remember to flush
      context.Response.Flush();
      context.Response.End();
    }

    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
}

The trick lies within the type casting of an Item to a MediaItem. The MediaItem contains a media stream that can be copied to the OutputStream of the HttpResponse.

Another trick is to construct a file name from the item name + the file extension found on the MediaItem. Adding this to the output stream will make the name appear as the default file name when users saves your file.

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, Sitecore 7 and tagged , , , . Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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