如何从文件扩展名中获得MIME类型?
当前回答
你可以使用这个helper函数:
private 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;
}
其他回答
您可以在注册表中找到这些信息。例如,.pdf文件的MIME类型可以在键HKEY_CLASSES_ROOT\.pdf中找到,在值"Content type "中:
string mimeType = Registry.GetValue(@"HKEY_CLASSES_ROOT\.pdf", "Content Type", null) as string;
FileExtension处理文件扩展名,而不是Mime。用户可以更改文件扩展名,因此请检查Mime。代码示例通过文件扩展名关联Mime,这是错误的,不能工作。
需要获取内容类型文件,并检查表Mime contetType该文件根据文件扩展名。现在,如何获得文件的内容类型?
使用FileUpload是这样的: 现在,如果我已经有文件,捕捉你的ContentType?
为了使这篇文章更全面,对于。net核心开发人员有FileExtensionContentTypeProvider类,它涵盖了官方的MIME内容类型。
它在幕后工作——根据文件扩展名在Http响应头中设置ContentType。
如果您需要特殊的MIME类型,请参阅自定义MIME类型的示例:
public void Configure(IApplicationBuilder app)
{
// Set up custom content types -associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages"),
ContentTypeProvider = provider
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
}
你可以使用mimemaps类。我认为这是最简单的方法。我也给出了mimemapping的导入。因为我觉得找这些类的导入很麻烦。
import org.springframework.boot.web.server.MimeMappings;
MimeMappings mm=new MimeMappings();
String mimetype = mm.get(fileExtension);
System.out.println(mimetype);
**使用MediaTypeNames类——>样本:MediaTypeNames. application . pdf **
推荐文章
- 最好的方法在asp.net强制https为整个网站?
- 在ASP .NET身份声明是什么
- 将字符串转换为System.IO.Stream
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 无法启动IIS Express Web服务器,注册URL失败,访问被拒绝
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- ASP。NET Identity DbContext混淆
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表