当前位置: 代码迷 >> ASP.NET >> MVC 文件动态上载,文件类型怎么指定?多谢
  详细解决方案

MVC 文件动态上载,文件类型怎么指定?多谢

热度:1963   发布时间:2013-02-25 00:00:00.0
MVC 文件动态下载,文件类型如何指定?谢谢
我现在有好多的文件可以下载,有rar打包的,有txt或者excel,MVC的文件下载方法
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
  string fileName = "test.txt";
  return File(new FileStream(path + fileName, FileMode.Open), "text/plain", fileName);

"text/plain", 是文件的类型,请问我如何可以动态设置这个参数,我试过用return File(path, "application/x-zip-compressed"); 
后面那个也是需要文件类型,请问如何解决这个问题,谢谢

------解决方案--------------------------------------------------------
加一个函数

return File(new FileStream(path + fileName, FileMode.Open), GetContentType(fileName), fileName);



private string GetContentType(string fileName)

{

string contentType = "application/octet-stream";

string ext = System.IO.Path.GetExtension(fileName).ToLower();

Microsoft.Win32.RegistryKey registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);

if (registryKey != null && registryKey.GetValue("Content Type") != null)

contentType = registryKey.GetValue("Content Type").ToString();

return contentType;

}

}
------解决方案--------------------------------------------------------
你下载文件,都设置成
"application/x-zip-compressed"
应该就可以了
  相关解决方案