回形针欺骗验证检查失败,因为file
命令无法准确确定文件类型。
在你的日志中content type discovered from file command: .
- 句点之前的空格是输出的结果 - 即空白。然而,比较的另一边纯粹使用文件扩展名,该扩展名被正确拾取为 Excel 文件。因此您的验证失败。
当前版本的 Paperclip 正在使用file -b --mime-type
但是要确定该文件--mime-type
并非所有实现都支持。有一个变化可以使用--mime
相反,但这还不是一个里程碑。
我认为你有一些选择。您选择哪个取决于您对某些可疑文件被上传并被称为 Excel 文件的担心程度。如果您担心这一点,请尝试选项 1;如果您不担心,请选择选项 2 或 3。
1) 覆盖欺骗检查以使用--mime
代替--mime-type
.
覆盖type_from_file_command
在初始化程序中:
module Paperclip
class MediaTypeSpoofDetector
private
def type_from_file_command
# -- original code removed --
# begin
# Paperclip.run("file", "-b --mime-type :file", :file => @file.path)
# rescue Cocaine::CommandLineError
# ""
# end
# -- new code follows --
begin
Paperclip.run("file", "-b --mime :file", :file => @file.path)
rescue Cocaine::CommandLineError
""
end
end
end
end
2)绕过file
通过完全根据文件扩展名设置文件类型来进行检查。
将此回形针选项设置在应用程序初始化期间读取的某个位置(例如config/application.rb
, config/environments/<environment>.rb
or an config/initializers/paperclip.rb
):
Paperclip.options[:content_type_mappings] = { xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
3)完全禁用欺骗。
通过在初始化程序中创建类似的内容来覆盖欺骗检查:
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
Update:
您在模型中进行的验证并不是导致此问题的原因。这将验证您可以加载哪些类型的文件;您所看到的是 Paperclip 计算出文件的类型有效,但其内容与文件的类型不匹配。
假设您可以使欺骗验证正常工作,则您的内容验证存在一个异常情况。您输出的错误消息显示“仅允许 XML、EXCEL 文件”,但是您的实际验证是检查 MS Word 和 Excel 文件,而不是 xml。
如果您的消息是正确的并且您确实只想允许 xml 和 excel 文件,您应该将 content_type 验证更改为:
validates_attachment_content_type :upload_file, :content_type => %w(application/xml application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet),
:message => ', Only XML,EXCEL files are allowed. '