How do I get the standard file extension given the MIME type in Delphi?

Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the simplest and most general way to implement a function that will be called like this:

fileExt := GetExtension('text/xml');

      

+3


source to share


3 answers


HKEY_CLASSES_ROOT \ MIME \ Database \ Content Type \ text / html value Extension.



+3


source


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.

+4


source


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;

      

+4


source







All Articles