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

馋奶兔 提交于 2019-11-29 06:54:19

问题


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.


回答1:


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.




回答2:


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

Mime::Type.lookup('image/jpeg').symbol.to_s
# => "jpg"


来源:https://stackoverflow.com/questions/16803389/rails-how-to-get-a-file-extension-postfix-based-on-the-mime-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!