Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?
I'm looking for the easiest and most general way to implement a function that would be called like this:
fileExt := GetExtension('text/xml');
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?
I'm looking for the easiest and most general way to implement a function that would be called like this:
fileExt := GetExtension('text/xml');
It seems Indy has a built in function for that, on TIdThreadSafeMimeTable:
Uses
IdCustomHTTPServer;
function GetMIMETypeDefaultExtension(const aMIMEType: String): String;
var
mimetable: TIdThreadSafeMimeTable;
Begin
if not(aMIMEType.Trim.IsEmpty) then
Begin
mimetable := TIdThreadSafeMimeTable.Create(true);
try
result := mimetable.GetDefaultFileExt(aMIMEType);
finally
mimetable.Free;
end
End
else
result := '';
End;
Edit: function fixed to use TIdThreadSafeMimeTable directly without custom http server.
Indy's IndyProtocols
package has a TIdMimeTable
class and standalone GetMIMETypeFromFile()
and GetMIMEDefaultFileExt()
wrapper functions in the IdGlobalProtocols
unit, eg:
uses
..., IdGlobalProtocols;
function GetExtension(const AMIMEType: string);
begin
Result := GetMIMEDefaultFileExt(AMIMEType);
end
Just know that internally, GetMIMEDefaultFileExt()
creates and destroys a TIdMimeTable
object, and that object re-builds its list of known extensions and MIME types every time it is created. If you are going to be querying MIME extensions frequently, it would be worth creating your own TIdMimeTable
object (or TIdThreadSafeMimeTable
if you need to share the table across multiple threads) and reuse it each time:
uses
..., IdGlobalProtocols;
var
MimeTable: TIdMimeTable = nil;
function GetExtension(const AMIMEType: string);
begin
if MimeTable = nil then
MimeTable := TIdMimeTable.Create;
Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;
initialization
finalization
MimeTable.Free;
uses
..., IdGlobalProtocols, IdCustomHTTPServer;
var
MimeTable: TIdThreadSafeMimeTable = nil;
function GetExtension(const AMIMEType: string);
begin
if MimeTable = nil then
MimeTable := TIdThreadSafeMimeTable.Create;
Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;
initialization
finalization
MimeTable.Free;
HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/html, value Extension.
For more current versions of Delphi, you can use the TMimeTypes
class in the unit System.Net.Mime
There are two methods which you can use to seed the internal dictionary to perform the lookup. The first AddDefTypes
will add the standard types, and the method AddOSTypes
will add any defined by the host OS (for windows, it does a registry crawl). If you call TMimeTypes.GetDefault
it will construct a TMimeTypes instance using both methods the first time it is called (singleton).