Skip to content

Instantly share code, notes, and snippets.

@harvzor
Last active August 13, 2018 20:41
Show Gist options
  • Save harvzor/b0b4e18b74c3ec9c361d to your computer and use it in GitHub Desktop.
Save harvzor/b0b4e18b74c3ec9c361d to your computer and use it in GitHub Desktop.
Create a document type in Umbraco called Download File and put this code into the template. When you want a user to download a file, direct them to example.com/downloadfile?id=####. The ID query string must be equal to a media items ID.
using Umbraco.Web;
using System.Web.Http;
using System.Web;
using System.IO;
namespace Examples.Service
{
public class DownloadServiceController : Umbraco.Web.Mvc.SurfaceController
{
// Use this if you only want logged in users to access these methods.
//[Umbraco.Web.WebApi.UmbracoAuthorize]
//[HttpGet]
/// /umbraco/surface/DownloadService/download?id=####&filename=document.doc
/// <summary>
/// Downloads an item from the Umbraco Media section to the users browser.
/// </summary>
/// <returns></returns>
public void Download(int id, string fileName)
{
var media = Umbraco.TypedMedia(id);
if (media != null)
{
// Get the physical path to the file.
string filePath = HttpContext.Server.MapPath(media.Url);
Download(filePath, fileName);
}
}
/// /umbraco/surface/DownloadService/download?filepath=####&filename=document.doc
/// <summary>
/// Downsloads a file based on the files path to the users browser.
/// </summary>
/// <returns></returns>
public void Download(string filePath, string fileName)
{
Response.ContentType = "application/force-download";
Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
// Write the file directly to the HTTP content output stream.
Response.WriteFile(filePath);
Response.End();
}
/// /umbraco/surface/DownloadService/download?buffer=####&filename=document.doc
/// <summary>
/// Turns a buffer into a downloadable file which is then sent to the users browser.
/// </summary>
/// <returns></returns>
public void Download(byte[] buffer, string fileName)
{
Response.ContentType = "application/force-download";
Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(buffer);
Response.End();
}
/// /umbraco/surface/DownloadService/download?stream=####&filename=document.doc
/// <summary>
/// Turns a stream into a downloadable file which is then sent to the users browser.
/// </summary>
/// <returns></returns>
public void Download(Stream stream, string fileName)
{
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
var buffer = memoryStream.ToArray();
Download(buffer, fileName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment