10 March 2014

MVC - Download a file from an action

It is often usefull for files to be downloaded through code, and not directly. In the case of MVC, the download would go via an action. In the following example I download a users profile picture that way, while the actual file is not accessible directly:
[Authorize]
public ActionResult Picture() {
  if (App.GetCurrentUser().HasPicture) { //Finds out if the current user has a picture in App_Data/UserPictures.
    io.FileStream stream = io.File.OpenRead(App.GetCurrentUser().PictureFilepath);
    byte[] data = new byte[stream.Length];
    stream.Read(data, 0, data.Length);
    stream.Close();
    stream.Dispose();
    return File(data, MediaTypeNames.Application.Octet, App.GetCurrentUser() + ".jpg");
  }
  else {
    return null;
  }
}
The file is read into memory and the streamed back as an action result of type File. This principle also allows for files to be generated on the fly without them ever being stored on disc.

No comments:

Post a Comment