Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream file from disk to client browser in .Net MVC

My action returns a file from disk to client browser and currently I have:

public FileResult MediaDownload ()
{
  byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(filePath));
  return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

This way it loads whole file in memory and is very slow, as the download start after the file is loaded to memory. What's the best way to handle such file downloads?

Thank you

like image 966
Burjua Avatar asked Oct 14 '14 13:10

Burjua


1 Answers

Ok, I came across this forum discussion: http://forums.asp.net/t/1408527.aspx

Works like a charm, exactly what I need!

UPDATE

Came across this question How to deliver big files in ASP.NET Response? and it turns out it's much simpler, here is how I do it now:

var length = new System.IO.FileInfo(Server.MapPath(filePath)).Length;
Response.BufferOutput = false;
Response.AddHeader("Content-Length", length.ToString());
return File(Server.MapPath(filePath), System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
like image 177
Burjua Avatar answered Nov 03 '22 16:11

Burjua