Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to get a file extension/postfix based on the mime type

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.

like image 233
LorneCurrie Avatar asked May 28 '13 23:05

LorneCurrie


People also ask

How do I get MIME type extension?

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).

What is MIME type of a file?

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.

Where is MIME type stored in a file?

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.

How do I get the extension of a MIME type in Python?

Once you use magic to get the MIME type, you can use mimetypes. guess_extension() to get the extension for it.


1 Answers

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.

like image 199
Andrew Marshall Avatar answered Nov 11 '22 16:11

Andrew Marshall