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.
Pingback: Which of my old Sitecore posts are still valid in Sitecore 9? | Brian Pedersen's Sitecore and .NET Blog