Monday, August 20, 2018

ASP.NET MVC - Handle binary or byte arrays as in file download

In ASP.NET MVC, downloading a file over http has been simplified and is user-friendly. The following code streams byte arrays to browser in two ways. GetFile would prompt for user dialog for choice as to Open or Save. OpenFile would try to stream the byte array content and render it in browser directly (pdf, etc). The sample code assumes that db.Binaries entity already has properties, such as BinaryData, MimeType and FileName, etc.
[HttpGet]
pulic FileContentResult GetFile(int id)
{
  var binary = db.Binaries.Find(id);
  if (binary == null)
  {
    return null;
  }
  byte[] binaryData = binary.BinaryData;
  string mimeType = binary.MimeType;
  string fileName = binary.FileName;

  return File(binaryData, mimeType, fileName);
}

[HttpGet]
public ActionResult OpenFile(int id)
{
  var binary = db.Binaries.Find(id);
  if (binary == null)
  {
    return null;
  }
  var contentDisposition = new System.Net.Mime.ContentDisposition
  {
    FileName = binary.FileName, Inline = false
  };
  Response.AddHeader("Content-Disposition", "inline; filename=" + binary.FileName);
  
  return File(binary.BinaryData, binary.MimeType);
}

No comments: