Rails:如何获得基于MIME类型的文件扩展名/后缀 [英] Rails: how to get a file extension/postfix based on the mime type
本文介绍了Rails:如何获得基于MIME类型的文件扩展名/后缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是,Ruby on Rails是否具有类似于以下功能:
Question I have is, does Ruby on Rails have a function similar to:
file_content_type = MIME::Types.type_for(file).first.content_type
将为特定的mime类型返回文件扩展名或后缀吗?因此,如果我输入"image/jpeg",该函数将返回"jpg"
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'
寻找一种更简洁的编码方式,而不必编写执行相同工作的case语句.
Looking for a cleaner way to code than having to write a case statement that does the same job.
推荐答案
Rack::Mime
具有此功能能力(机架是Rails的依赖项):
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.
这篇关于Rails:如何获得基于MIME类型的文件扩展名/后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文