Given the variable content_type = "application/pdf"
that can also include any other mime type.
给定变量content_type =“application / pdf”,其还可以包括任何其他mime类型。
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?
有更好的解决方案吗?
2 个解决方案
#1
3
Your second solution with the mime type is the solution, which you should choose. There are several reasons for that:
您使用mime类型的第二个解决方案是您应该选择的解决方案。有几个原因:
- The second solution is exactly designed for your use case
-
Hack the string
could be inconsistent or return unexpected results (think aboutapplication/postscript
has the extensioneps
!) - Please consider, that we probably can't say, that every mime type has it's default extension. For example: who has defined the default extension for jpg (or jpeg or JPG..) images?
第二种解决方案是专为您的用例而设计的
Hack字符串可能不一致或返回意外结果(想想application / postscript有扩展名eps!)
请考虑,我们可能不能说,每个mime类型都有它的默认扩展名。例如:谁为jpg(或jpeg或JPG ..)图像定义了默认扩展名?
#2
10
All you need to is use ruby's Hash.invert
method.
您需要的只是使用ruby的Hash.invert方法。
This answer shows how to do it:
这个答案显示了如何做到这一点:
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.
如果您要经常进行查找,您可能希望记住反向哈希,因为它不是一个便宜的操作。
From your tags, it seems you are using rails anyway.
从你的标签来看,无论如何你似乎都在使用rails。
#1
3
Your second solution with the mime type is the solution, which you should choose. There are several reasons for that:
您使用mime类型的第二个解决方案是您应该选择的解决方案。有几个原因:
- The second solution is exactly designed for your use case
-
Hack the string
could be inconsistent or return unexpected results (think aboutapplication/postscript
has the extensioneps
!) - Please consider, that we probably can't say, that every mime type has it's default extension. For example: who has defined the default extension for jpg (or jpeg or JPG..) images?
第二种解决方案是专为您的用例而设计的
Hack字符串可能不一致或返回意外结果(想想application / postscript有扩展名eps!)
请考虑,我们可能不能说,每个mime类型都有它的默认扩展名。例如:谁为jpg(或jpeg或JPG ..)图像定义了默认扩展名?
#2
10
All you need to is use ruby's Hash.invert
method.
您需要的只是使用ruby的Hash.invert方法。
This answer shows how to do it:
这个答案显示了如何做到这一点:
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.
如果您要经常进行查找,您可能希望记住反向哈希,因为它不是一个便宜的操作。
From your tags, it seems you are using rails anyway.
从你的标签来看,无论如何你似乎都在使用rails。