我最近从 Carrierwave 1.3 升级到 2.1,并且由于 MIME 类型无效而导致一些规范失败。
我存储在数据库、CSV 上传中,并在模型上验证 mime 类型是否为 text/csv
。
validates :file, presence: true, file_content_type: {
allow: [
'text/csv',
'application/vnd.ms-excel',
'application/vnd.ms-office',
'application/octet-stream',
'text/comma-separated-values'
]
}
根据规范,我创建了一个装置
let(:file) { Fixture_file_upload('files/fixture.csv', 'text/csv') }
当我调试时,
@file=
#<CarrierWave::SanitizedFile:0x00007f8c731791f0
@content=nil,
@content_type="invalid/invalid",
@file="/Users/tiagovieira/code/work/tpc/public/uploads/csv_file_upload/file/1/1605532759-308056149220914-0040-7268/fixture.csv",
@original_filename="fixture.csv">,
@filename="fixture.csv",
@identifier="fixture.csv",
这是否与 Carrierwave 停止使用 mime-types
gem 作为依赖项有关?
最佳答案
看来问题已经找到了。
在之前的 Carrierwave 版本中,“CarrierWave::SanitizedFile” content_type 是通过扩展计算的 https://github.com/carrierwaveuploader/carrierwave/blob/1.x-stable/lib/carrierwave/sanitized_file.rb
def content_type
return @content_type if @content_type
if @file.respond_to?(:content_type) and @file.content_type
@content_type = @file.content_type.to_s.chomp
elsif path
@content_type = ::MIME::Types.type_for(path).first.to_s
end
end
现在有更复杂的方法。它使用算法根据文件包含的数据来识别文件类型。
https://github.com/carrierwaveuploader/carrierwave/blob/master/lib/carrierwave/sanitized_file.rb
def content_type
@content_type ||=
existing_content_type ||
mime_magic_content_type ||
mini_mime_content_type
end
我在 mime_magic_content_type
之后有“无效/无效”内容类型,它似乎无法使用“MimeMagic.by_magic”获取文件类型。
PS 我看到通常的 css 文件返回“plain/text”content_type。 https://github.com/minad/mimemagic/blob/master/lib/mimemagic/tables.rb#L1506
关于ruby-on-rails - Carrierwave 将 mime 类型设置为无效/无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64859491/