LA.NET [EN]

Feb 12

The latest release of the MVC platform introduces some classes which simplifies the code you need to write when you need to work with files. Today, we’re going to concentrate on the available options you can use when you need to download a file from an action method. We’ll start by looking at the base FileResult abstract class.

This class exposes only a public constructor which receives a string. This string is used for identifying the content type of the file that is going to be downloaded. The class also introduces a public property (with a getter and a setter) which you can use to define the name that is shown on the download dialog that is presented to the user when the action is executed and the file returned.

Finally, the class implements the ExecuteResult by defining the content-type and content-disposition headers which are returned to the client. The process of writing the contents of the file to the response stream are delegated to the derived classes (which must implement the abstract WriteFile method).

Currently, the platform introduces three concrete instances of the FileResult type. Your first option is using FileContentResult.You should use this type whenever you have the bytes of the file you want to return. If you’ve got  a reference to the a stream, then you can also use the FileStreamResult class. As you’ve guessed, you’ll need to pass a reference to the stream you want to write to the response that is returned to the client. Do keep in mind that the class ends up calling Dispose on this stream after copying to the  response stream that is returned to the client.

Finally, if you’ve got a physical location to a file that you want to return to the client, you can use the FilePathResult class. This file is pretty simple and it will simply call Response.TransmitFile and pass it the path you’ve previously sent into its constructor.

Returning files hasn’t been easier! On the next post we’ll keep looking at the MVC platform. Stay tuned!

1 comment so far

  1. ricka
    8:29 pm - 2-19-2009

    Nice. Looking forward to the next post.