1

I'm using ASP MVC, and I want to allow the user to download/view files from my web server.

The files are not located in this web server.

I know the file content (a byte[] array), and also the file name.

I want same behavior that as the Web Broswer. For example, if the mime type is text, I want to see the text, if it's an image, the same, if it's binary, propose it for a download.

What is the best way to do this?

Thanks in advanced.

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219

1 Answers1

0

The answer for images is available here

For other types, you have to determine the MIME type from the file name extension. You can use either the Windows Registry or some well-known hashtable, or also IIS configuration (if running on IIS).

If you plan to use the registry, here is a code that determines the MIME content type for a given extension:

    public static string GetRegistryContentType(string fileName)
    {
        if (fileName == null)
            throw new ArgumentNullException("fileName");

        // determine extension
        string extension = System.IO.Path.GetExtension(fileName);

        string contentType = null;
        using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(extension))
        {
            if (key != null)
            {
                object ct = key.GetValue("Content Type");
                key.Close();
                if (ct != null)
                {
                    contentType = ct as string;
                }
            }
        }
        if (contentType == null)
        {
            contentType = "application/octet-stream"; // default content type
        }
        return contentType;
    }
Community
  • 1
  • 1
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • My web server will be IIS or XSP (mono), so I cannot assume that I can access a Windows Registry :-( – Daniel Peñalba Dec 01 '10 at 13:42
  • 1
    ohh... you can always go for a fixed list then. There is a list available here as a start: http://www.w3schools.com/media/media_mimeref.asp – Simon Mourier Dec 01 '10 at 13:53
  • Thanks for the info. I was thinking in implement two providers (for linux or windows), but finally I will manage a fixed list (I will take the mime.types file from the apache server) – Daniel Peñalba Dec 01 '10 at 13:59