How do I get the standard file extension given the MIME type in Delphi?
Indy seems to have a built in function for 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: Fixed being able to use TIdThreadSafeMimeTable directly without a custom HTTP server.
source to share
Indy IndyProtocols
package has TIdMimeTable
class and standalone GetMIMETypeFromFile()
and GetMIMEDefaultFileExt()
wrapper functions in module IdGlobalProtocols
, for example:
uses
..., IdGlobalProtocols;
function GetExtension(const AMIMEType: string);
begin
Result := GetMIMEDefaultFileExt(AMIMEType);
end
Just know what GetMIMEDefaultFileExt()
creates and destroys an object internally TIdMimeTable
, and that object re-creates its list of known extensions and MIME types each time it is created. If you are going to query MIME extensions frequently, it would be wise to create your own TIdMimeTable
object (or TIdThreadSafeMimeTable
if you need to split the table across multiple threads) and use it every 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;
source to share