Monday 1 September 2014

Force File Download

Sometimes instead of letting a user view an Image or PDF I would rather them download it, This method below Forces the File (Doc / MP3 / PDF / Images) etc.. to be downloaded rather than rendered. This can save time and bandwidth on a website rather than the user continaully streaming the data on a frequent basis.
namespace FieldOfSheep
{
public class FileDownloadExtensions
{
 public static void ForceFileDownload(MemoryStream s, string fileName)
        {
            if (HttpContext.Current != null)
            {
                var responseObject = HttpContext.Current.Response;

                if (responseObject.IsClientConnected && s != null)
                {
                    responseObject.Clear();
                    responseObject.ContentType = "application/octet-stream";
                    responseObject.AddHeader("Content-Disposition",
                        "attachment; filename=" + fileName);

                    responseObject.BinaryWrite(s.ToArray());

                    responseObject.Flush();

                    responseObject.Close();
                }
            }
        }
 }
}       

No comments:

Post a Comment