Carrierwave将mime类型设置为无效/无效



我最近从Carrierwave 1.3升级到2.1,由于mime类型无效,我有几个规范失败了。

我在数据库中存储CSV Uploads,并在模型中验证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-typesgem作为依赖项有关?

似乎发现了问题。

在先前的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

我有";无效/无效";CCD_ 4之后的内容类型;MimeMagic.by_magic"。

PS我看到";"纯文本";对于通常的css文件,返回content_type。https://github.com/minad/mimemagic/blob/master/lib/mimemagic/tables.rb#L1506

使用Rack::Test::UploadedFile

为安装的模型分配Rack::Test::UploadedFile对象假设你的模型是:

class User < ApplicationRecord
mount_uploader :file, FileUploader
end

要测试上传程序,您可以使用以下内容:

user.file = Rack::Test::UploadedFile.new(File.open('test_file.csv'), "text/csv")
user.save

Carrierwave的content_type_whitelist或extension_whitelit的白名单

class FileUploader < CarrierWave::Uploader::Base
private
def extension_whitelist
%w(csv xlsx xls)
end
def content_type_whitelist
[
'text/csv',
'application/vnd.ms-excel',
'application/vnd.ms-office',
'application/octet-stream',
'text/comma-separated-values'
]
end
end

同时检查:https://til.codes/testing-carrierwave-file-uploads-with-rspec-and-factorygirl/