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

后端 未结 2 573
终归单人心
终归单人心 2020-12-29 07:10

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 w

相关标签:
2条回答
  • 2020-12-29 07:55

    A better more up to date answer, since I found this googling.

    Mime::Type.lookup('image/jpeg').symbol.to_s
    # => "jpg"
    
    0 讨论(0)
  • 2020-12-29 07:57

    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.

    0 讨论(0)
提交回复
热议问题