我正在使用 ASP MVC ,我希望允许用户从我的网络服务器下载/查看文件。
这些文件不在此Web服务器中。
我知道文件内容(一个byte[]
数组),还有文件名。
我想要和Web Broswer一样的行为。例如,如果mime类型是文本,我想看到文本,如果是图像,则相同,如果它是二进制文件,则建议下载。
这样做的最佳方式是什么?
先谢谢。
答案 0 :(得分:0)
图片的答案可用here
对于其他类型,您必须从文件扩展名中确定MIME类型。您可以使用Windows注册表或一些众所周知的哈希表,也可以使用IIS配置(如果在IIS上运行)。
如果您打算使用注册表,这里有一个代码,用于确定给定扩展名的MIME内容类型:
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;
}