Downloading the Media item on WFFM from submission

I have seen that many developers are searching for a solution for downloading the media item on successful submission of a WFFM form, But I couldn’t find an exact solution over the internet and that’s where I thought of putting this to help the community.

So here is the solution.

  1. Add a field to your form and hide it using the tricks I explained in one of my previous posts. You can find that here- Hide a field on WFFM (No CSS & JS)
  2. Give that field a default value and that value should be the Media Item Id.
  3. Now come to the code. You need to create a custom save action to achieve this. Have a look at my code.
using System;
using System.Collections.Generic;
using System.Net;
using System.Web;
using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.WFFM.Abstractions.Actions;
using Sitecore.WFFM.Abstractions.Shared;
using Sitecore.WFFM.Actions.SaveActions;
using Sitecore.Data.Items;
using Sitecore;

namespace SitecoreTricks
{
 public class DownloadMediaOnSuccess : SendMessage
 {
 public DownloadMediaOnSuccess (ISettings settings, IMailSender mailSender) : base(settings, mailSender)
 {}

public override void Execute(ID formId, AdaptedResultList adaptedFields,
 ActionCallContext actionCallContext = null,
 params object[] data)
 {

 var formData = new Dictionary<string, string>();
 foreach (AdaptedControlResult acr in adaptedFields)
 {
 formData.Add(acr.FieldName, acr.Value);
 }
var MediaItemId = !string.IsNullOrEmpty(formData["FileToDownload"])
? formData["FileToDownload"]
: string.Empty;

var item = Context.Database.GetItem(new ID(MediaItemId));
 var mediaItem = (MediaItem) item;

HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.ContentType = mediaItem.MimeType;
 HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("inline;filename=\"{0}\"", mediaItem.Name+"."+mediaItem.Extension));
 HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.OK;
 HttpContext.Current.Response.BufferOutput = true;
 mediaItem.GetMediaStream().CopyTo(HttpContext.Current.Response.OutputStream);
 HttpContext.Current.Response.Flush();
 HttpContext.Current.Response.End();

} 
 }
 }

That’s it. The PDF will be opened in the browser from there you can download it.

Reference: Learn how to hide a field on a WFFM form

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s