Given the variable content_type = "application/pdf"
that can also include any other mime type.
How can I get the default extension for the content type?
I have currently two solutions, which seem very "complicated".
Hack the string
content_type.split("/")[1]
Use MIME::Types
require 'mime/types'
MIME::Types[content_type].first.extensions.first
Is there a better solution?
string mimeType = System. Web. MimeMapping. GetMimeMapping(fileName);
A media type (also known as a MIME type) is a two-part identifier for file formats and format contents transmitted on the Internet. The Internet Assigned Numbers Authority (IANA) is the official authority for the standardization and publication of these classifications.
All you need to is use ruby's Hash.invert
method.
This answer shows how to do 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.
From your tags, it seems you are using rails anyway.
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