MVC3 - How to output a file to download without sa

2019-04-24 11:00发布

问题:

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?

回答1:

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");
    }


回答2:

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.



回答3:

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