I have a file browser application in MVC4 that allows you to download a selected file from a controller.
Currently, the FileResult returns the Stream of the file, along with the other response headers. While this works fine for smaller files, files that are larger generate an OutOfMemoryException.
What I'd like to do is transmit the file from the controller, without buffering in memory in a fashion similiar to HttpReponse.TransmitFile in WebForms.
How can this be accomplished?
Yes you can by using Web Api in order to stream the file, take a look at this article Dealing with large files in ASP.NET Web API
Additionaly to the above link describing configuration, you may use TransmitFile to "stream" files. However, TransmitFile has some backwards on some http clients.
This is my code to "stream" files to client, as an alternative for TransmitFile. Note that I've have a config constant to rollback with WriteFile (which have the same OutOfMemory issue as yours) :
method code :
I used this code to avoid some problems in streaming pdf files to old acrobat reader plugin. For the inline parameter, you may use "false".
Additionaly, you may use try/catch around this code, as any of Response.IsClientConnecter/Write/Flush can throw exceptions if client disconnect.
However, I'm not using MVC, and I'm not sure this is acceptable for this techno, as if you have not used TransmitFile, you may be stuck with the same issue with this code. If you are trying to embedd files into web pages element (as base64 maybe ?) this is not the solution.
Let me know more information about your requirements, if you need others ways to achieve your goals.
You can disable the response buffer before you return the file result.