|
using System;
using System.Web.Mvc;
namespace MvcBasicSite.Models.Helpers
{
/// <summary>
/// Defines the open file in new window action result.
/// </summary>
public class OpenFileResult : ActionResult
{
/// <summary>
/// The request IsLocal flag.
/// </summary>
private bool _isLocal = false;
/// <summary>
/// The virtual path of the file.
/// </summary>
public string VirtualPath
{
get;
set;
}
/// <summary>
/// The file name with extension and without path.
/// </summary>
public string FileName
{
get;
set;
}
/// <summary>
/// Gets or sets the content type.
/// </summary>
public string ContentType { get; set; }
/// <summary>
/// Initializes a new instance of the OpenFileResult class.
/// </summary>
/// <param name="isLocal">The request IsLocal flag.</param>
/// <param name="virtualPath">The file virtual path or use the default Doc path.</param>
public OpenFileResult(bool isLocal, string virtualPath)
{
_isLocal = isLocal;
this.VirtualPath = virtualPath;
}
/// <summary>
/// Open the file into a new browser window for known files or let the user to select Open/Save.
/// </summary>
/// <param name="context">The current controller context.</param>
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ClearContent();
//
if(this.ContentType != null)
context.HttpContext.Response.ContentType = ContentType;
else
context.HttpContext.Response.AddHeader("content-disposition", "attachment;filename=" + this.FileName);
//
context.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
string filePath = (_isLocal ? this.FileName : string.Format("{0}\\{1}", context.HttpContext.Server.MapPath(this.VirtualPath), this.FileName));
if (System.IO.File.Exists(filePath))
{
context.HttpContext.Response.TransmitFile(filePath);
}
else
{
context.HttpContext.Response.Write(Resources.Resource.OpenFileResultFileNotFound);
}
//
context.HttpContext.Response.End();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I have about 20 years experiences in leading software projects and teams and about 25 years of working experience in software development (SW Developer, SW Lead, SW Architect, SW PM, SW Manager/Group Leader).