MimeParser - mojtabanabavi/Loby.AspNetCore GitHub Wiki
About
Provides a two-way mapping of file extensions to mime types and mime types to file extensions.
Namespace
Loby.AspNetCore.Helpers
Map mime types to file extensions
For mapping mime types to file extensions there is two functions.
string ToExtension(string mimeType);
string ToExtension(string mimeType, string defaultExtension);
The ToExtension(string mimeType)
, only requires one string parameter. If it can't find a suitable file extension for mime, will return an empty string.
see the below sample:
string pdfMimeType = "application/pdf";
string pdfExtension = MimeParser.ToExtension(pdfMimeType);
The ToExtension(string mimeType, string defaultExtension)
, requires two parameters. If it can't find a suitable file extension for mime, will return the specified defaultExtension
.
see the below sample:
string pngMimeType = "image/x-png";
string defaultExtension = ".png";
string pngExtension = MimeParser.ToExtension(pngMimeType, defaultExtension);
Map file extensions to mime types
For mapping file extensions to mime types there is two functions.
string ToMimeType(string extension);
string ToMimeType(string extension, string defaultMimeType);
The ToMimeType(string extension)
, only requires one string parameter. If it can't find a suitable mime type for file extension, will return application/octet-stream
that is used for unknown binary files.
see the below sample:
string mp4Extension = ".mp4";
string mp4MimeType = MimeParser.ToMimeType(mp4Extension);
The ToMimeType(string extension, string defaultMimeType)
, requires two parameters. If it can't find a suitable mime type for file extension, will return the specified defaultMimeType
.
see the below sample:
string mkvExtension = ".mkv";
string defaultMimeType = "video/mp4";
string videoMimeType = MimeParser.ToMimeType(mkvExtension, defaultMimeType);
Extend the parser
The Mime Parser supports most of mime types and file extensions, but what if there is not any mappings for your inputs?
You can easily extend the parser by adding your custom mappings using the AddMapping(string key, string value)
function.
This function adds a two-way mapping of file extension to mime type and mime type to file extension at once.
see the below sample:
string myCustomExtension = ".unknown";
string myCustomMimeType = "application/unknown";
MimeParser.AddMapping(myCustomExtension, myCustomMimeType);