In PHP, it is possible to return a file to the browser by echoing it out with the correct header. You do not need to save a copy of it prior on the server.
So assuming I have a bunch of data I wish to return as a excel file - after creating the data structure using OpenXML, how can I serve the file to the user without saving it on the server first?
Write your data to a stream and return it from your controller action method in a FileStreamResult by setting the FileStream
, ContentType
and FileDownloadName
properties.
[HttpGet]
public FileStreamResult MyFile()
{
var fileStreamResult = new FileStreamResult (GetMyContentAsStream(), "my/content-type-here");
fileStreamResult.FileDownloadName = "my-file-download-name.here";
return fileStreamResult ;
}
Update:
A short cut for doing this, is to use the Controller.File() method.
[HttpGet]
public FileStreamResult MyFile()
{
return File(GetMyContentAsStream(), "my/content-type-here");
}
It's pretty simple actually. In your controller you can have an action like this:
public ActionResult GetMyFile()
{
//dynamically generate a file
System.IO.MemoryStream ms;
ms = GenerateFile(); // Some function to return a memorystream object
// return the file
return File(ms.ToArray(), "filename.pdf");
}
The user will be presented with a dialog box asking if they want to open the file or save it.
You can save the contents of your dynamically generated file in a MemoryStream
object. When you return a file you can use MemoryStream's GetBuffer()
method to pass an array of bytes as the first parameter. Then set ContentType
and FileDownloadName
parameters.
Regards