0

I have the following issue: ASP-MVC I want to put a file in a folder in IIS and allow users surfing my site to download it.

In my site, I will have a link that points to an action method in my controller, and within this method I want to put the needed code. Never dealt with this issue before, will appriciate a code sample. Thanks!

Cod Fish
  • 917
  • 1
  • 8
  • 37

2 Answers2

0

This code , taken from this question, will accomplish what you want.

public FileResult Download()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes("c:\folder\myfile.ext");
    string fileName = "myfile.ext";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Community
  • 1
  • 1
Atilla Ozgur
  • 14,339
  • 3
  • 49
  • 69
0

Assuming you want to get a specific file based on some passed-in ID, you can use the Controller.File function as described here: http://msdn.microsoft.com/en-us/library/dd492492(v=vs.100).aspx

Here's an example controller function from that page:

public ActionResult ShowFileFN(string id) {
  string mp = Server.MapPath("~/Content/" + id);
  return File(mp, "text/html");
}

This will return a binary stream of the named file with the specified MIME content type, in this case "text/html". You'll need to know the MIME type for each file you're returning.

Here's a function to get the MIME type of a file based on its extension:

public static string GetMimeType(string fileName)
{
    string mimeType = "application/unknown";
    string ext = System.IO.Path.GetExtension(fileName).ToLower();
    Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
    if (regKey != null && regKey.GetValue("Content Type") != null)
        mimeType = regKey.GetValue("Content Type").ToString();
    return mimeType;
}
Lee Greco
  • 743
  • 2
  • 11
  • 23