How can i know mime type of file with Erlang?
Thank you.
If you want to know the mime type of a file based on its extension you can use the undocumented inets function httpd_conf:load_mime_types/1. This together with a mime.types file (there's one in one of the inets httpd examples in OTP) will give you a list of file extensions and their default associated mime types. The following code will give you the standard mime type for a given filename based on its extension:
mime_type(FileName) ->
"." ++ Extension = filename:extension(FileName),
MimeTypes = mime_types(),
proplists:get_value(Extension, MimeTypes).
mime_types() ->
MimeTypesFile = filename:join(code:lib_dir(inets),
"examples/server_root/conf/mime.types"),
{ok, MimeTypes} = httpd_conf:load_mime_types(MimeTypesFile),
MimeTypes.
You can now use mime_type/1 on a filename (e.g. example.pdf) and it will return you the default mime type if known (in this case "application/pdf") or undefined otherwise.
If you're going to do this operation repeatedly, it would be a good idea to cache the result of httpd_conf:load_mime_types/1 as the inets httpd server does, so that you avoid reading and parsing the mime types file all the time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With