Monday, October 03, 2011

How to stream a File in MVC

In Classic ASP or ASP .Net, you can simply change the response type and start writing binary. In MVC you have a Controller method which returns an ActionResult. So this class will properly provide that :


public class BinaryResult : ActionResult
{
private byte[] _fileBinary;
private string _contentType;
private string _fileName;

public BinaryResult(byte[] fileBinary, string contentType, string fileName)
{
_fileBinary = fileBinary;
_contentType = contentType;
_fileName = fileName;
}

public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Clear();
context.HttpContext.Response.ContentType = _contentType;
context.HttpContext.Response.AddHeader("Content-Disposition",
"filename=" + _fileName);

if (_fileBinary != null)
{
context.HttpContext.Response.BinaryWrite(_fileBinary);
}
}
}


In my case the only other challenge was getting the Byte array prepared, because I had to call Convert.FromBase64String, because of the way the data was stored.

No comments: