开发者

Web: View raw content of a file from the FileName and the FileContent

开发者 https://www.devze.com 2023-01-28 00:22 出处:网络
I\'m using ASP MVC, and I want to allow t开发者_如何转开发he user to download/view files from my web server.

I'm using ASP MVC, and I want to allow t开发者_如何转开发he 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.


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;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消