ruby-on-rails – 验证失败:上传文件的扩展名与其内容不匹配
我正在使用paperclip gem上传文件.而我的回形针宝石版是paperclip-4.1.1.在上传一个文件的扔
Validation failed: Upload file has an extension that does not match its contents. 我正在尝试上传一个xlsx文件.并且我也提到了模型content_type. validates_attachment_content_type :upload_file,:content_type => %w(application/msword application/vnd.ms-office application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet),:message => ',Only XML,EXCEL files are allowed. ' 我不知道为什么这个错误发生.如果您有任何关于此错误的想法,请分享. 从日志显示验证失败: Command :: file -b --mime-type '/tmp/5249540099071db4e41e119388e9dd6220140513-24023-1jlg4zy' [paperclip] Content Type Spoof: Filename file_for_bulk_upload1.xlsx (["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]),content type discovered from file command: . See documentation to allow this combination. Command :: file -b --mime-type '/tmp/6f19a4f96154ef7ce65db1d585abdb2820140513-24023-tt4u1e' [paperclip] Content Type Spoof: Filename file_for_bulk_upload1.xlsx (["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]),content type discovered from file command: 解决方法
Paperclip欺骗验证检查失败,因为文件命令无法准确确定文件类型.
在从file命令中发现的日志内容类型中. – 期间之前的空格是输出的结果 – 即空白.但是,比较的另一面纯粹是使用正确的Excel文件扩展名.因此您的验证失败. 当前版本的Paperclip正在使用文件-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)通过从文件扩展名完全设置文件类型来绕过文件检查. 将此Paperclip选项设置为在应用程序初始化期间读取的位置(例如,config / application.rb,config / environments /< environment> .rb或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 更新: 您在模型中的验证不是导致此问题的原因.这将验证您允许加载哪些类型的文件;您看到的是Paperclip,计算文件的类型是有效的,但其内容与文件的类型不匹配. 假设您可以使欺骗验证工作,您的内容验证有一个异常.您输出的错误消息说“只允许XML,EXCEL文件”,但是您的实际验证是检查MS字和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),EXCEL files are allowed. ' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |