Rails:如何根据mime类型获取文件扩展名/后缀

时间:2021-07-27 20:07:18

Question I have is, does Ruby on Rails have a function similar to:

我的问题是,Ruby on Rails是否具有类似于以下功能:

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'

这将返回特定mime类型的文件扩展名或后缀?所以,如果我传入'image / jpeg',该函数将返回'jpg'

Looking for a cleaner way to code than having to write a case statement that does the same job.

寻找一种更清晰的代码编写方式,而不是编写执行相同工作的case语句。

2 个解决方案

#1


34  

Rack::Mime has this ability (and Rack is a dependency of Rails):

Rack :: Mime有这种能力(而Rack是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


0  

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

一个更好的更新答案,因为我发现这个谷歌搜索。

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

#1


34  

Rack::Mime has this ability (and Rack is a dependency of Rails):

Rack :: Mime有这种能力(而Rack是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


0  

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

一个更好的更新答案,因为我发现这个谷歌搜索。

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