Question I have is, does Ruby on Rails have a function similar to:
file_content_type = MIME::Types.type_for(file).first.content_type
that will return the file extension or postfix for a specific mime type? So if I pass in 'image/jpeg' the function will return 'jpg'
Looking for a cleaner way to code than having to write a case statement that does the same job.
string mimeType = MimeMapping. GetMimeMapping(fileName); If you need to add custom mappings you probably can use reflection to add mappings to the BCL MimeMapping class, it uses a custom dictionary that exposes this method, so you should invoke the following to add mappings (never tested tho, but should prob. work).
A unique file name extension that is specified by the fileExtension attribute, for example, ". txt", ". png", etc. A MIME type for the file name extension that is specified by the mimeType attribute, for example, "text/plain", "image/jpg", etc.
All MIME type information is stored in a database. The MIME database is located in the directory /usr/share/mime/ . The MIME database contains a large number of common MIME types, stored in the file /usr/share/mime/packages/freedesktop.
Once you use magic to get the MIME type, you can use mimetypes. guess_extension() to get the extension for it.
Rack::Mime
has this ability (and Rack is a dependency of Rails):
require 'rack/mime'
Rack::Mime::MIME_TYPES.invert['image/jpeg'] #=> ".jpg"
You may wish to memoize the inverted hash if you’re going to do the lookup often, as it’s not an inexpensive operation.
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