In an MVC application, we are offering the functionality to download files. This is easy thanks to the built-in FileResult class.
The only caveat is that we have to support a wide range of file formats. To make the browser react correctly it’s important to set the correct MIME type in the response. Before ASP.NET 4.5 you had to build your own list of mappings between a file extension and the related MIME type. Luckily, in .NET 4.5, this is no longer required. The MimeMapping class exposes a public static method called GetMimeMapping which takes in a file name (or extension) and returns the appropriate MIME type:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult Download(string filePath, string fileName) | |
{ | |
var fullName = Path.Combine(GetBaseDir(), filePath, fileName); | |
var file = GetFile(fullName); | |
return File(file, MimeMapping.GetMimeMapping(fileFromDB.FileName), fileName); | |
} | |