Rails:.m4v文件的MIME类型问题

时间:2010-03-10 04:17:48

标签: ruby-on-rails mime-types

在我的Rails应用程序中,我试图获取文件的MIME类型,如下所示:

MIME::Types.type_for("example.m4v").to_s

但它没有认识到它。

我尝试将以下内容添加到config/initializers/mime_types.rb(并重新启动服务器),但没有任何运气:

Mime::Type.register "video/mp4", :m4v

2 个答案:

答案 0 :(得分:8)

您需要将以下行添加到config/initializers/mime_types.rb文件中:

# register MIME type with Rails 
Mime::Type.register "video/mp4", :m4v

# register MIME type with MIME::Type gem 
MIME::Types.add(MIME::Type.from_array("video/mp4", %(m4v)))

现在在控制台中,您可以测试结果

MIME::Types.type_for("abc.m4v").to_s
#=> "video/mp4"

答案 1 :(得分:0)

所以我认为Mime :: Type和MIME :: Types彼此完全分开。请注意,它是“Mime”vs“MIME”。

例如,

MIME::Types.type_for("foo.json") 

返回

 [#<MIME::Type:0x1038b3108 @system=nil, @encoding="8bit", @simplified="application/json", @sub_type="json", @registered=true, @url=["IANA", "RFC4627"], @docs=nil, @obsolete=nil, @extensions=["json"], @raw_sub_type="json", @media_type="application", @raw_media_type="application", @content_type="application/json">]

然而,

Mime::Type.lookup_by_extension("json")

返回

#<Mime::Type:0x1051c4d40 @symbol=:json, @string="text/x-json", @synonyms=[]>

所以看起来如果你想添加一个类型,以便在使用type_for时返回它,你可以使用以下内容:

>> t = MIME::Type.from_array('video/mp4', %w(m4v))
=> #<MIME::Type:0x1055de3b8 @system=nil, @encoding="base64", @simplified="video/mp4", @sub_type="mp4", @registered=true, @url=nil, @docs=nil, @obsolete=nil, @extensions=["m4v"], @raw_sub_type="mp4", @media_type="video", @raw_media_type="video", @content_type="video/mp4">
>> MIME::Types.add(t)
Type video/mp4 already registered as a variant of video/mp4.
=> [#<MIME::Type:0x1055de3b8 @system=nil, @encoding="base64", @simplified="video/mp4", @sub_type="mp4", @registered=true, @url=nil, @docs=nil, @obsolete=nil, @extensions=["m4v"], @raw_sub_type="mp4", @media_type="video", @raw_media_type="video", @content_type="video/mp4">]
>> MIME::Types.type_for("example.m4v")
=> [#<MIME::Type:0x1055de3b8 @system=nil, @encoding="base64", @simplified="video/mp4", @sub_type="mp4", @registered=true, @url=nil, @docs=nil, @obsolete=nil, @extensions=["m4v"], @raw_sub_type="mp4", @media_type="video", @raw_media_type="video", @content_type="video/mp4">]
>>

调用add时的警告有点令人担忧,因此您应该弄清楚如何将扩展名附加到“video / mp4”类型。有关详细信息,请查看MIME::TypesMIME::Type的文档。