Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the default extension for a given content type?

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?

like image 612
ayckoster Avatar asked Feb 08 '13 10:02

ayckoster


People also ask

How do I get mime type extension?

string mimeType = System. Web. MimeMapping. GetMimeMapping(fileName);

What is file MIME type?

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.


1 Answers

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.

like image 74
Vedant Agarwala Avatar answered Sep 21 '22 23:09

Vedant Agarwala