Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 - How to output a file to download without saving it on the server first?

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?

like image 852
Extrakun Avatar asked Aug 17 '11 05:08

Extrakun


3 Answers

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.

like image 113
Anthony Queen Avatar answered Sep 29 '22 12:09

Anthony Queen


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");
    }
like image 27
John Mills Avatar answered Sep 29 '22 13:09

John Mills


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

like image 42
Husein Roncevic Avatar answered Sep 29 '22 13:09

Husein Roncevic