Paperclip is not supporting .doc file

shu*_*hra 3 ruby validation ruby-on-rails file paperclip

In rails 4.0.2, I am using paperclip gem to upload files. But it is not supporting .doc file. Below the file upload field, it is showing an error message as "has an extension that does not match its contents"

In model, the validation for checking the content type is given below :

validates_attachment_content_type :document, :content_type => ['application/txt', 'text/plain',
'application/pdf', 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.oasis.opendocument.text',
'application/x-vnd.oasis.opendocument.text',
'application/rtf', 'application/x-rtf', 'text/rtf', 
'text/richtext', 'application/doc', 'application/docx', 'application/x-soffice', 'application/octet-stream']
Run Code Online (Sandbox Code Playgroud)

Gems which is used right now

rails (4.0.2, 4.0.0, 3.2.13, 3.2.8, 3.0.4, 3.0.3)

paperclip (3.5.2, 2.3.11, 2.3.8)
Run Code Online (Sandbox Code Playgroud)

How can I solve this issue?

urj*_*ils 8

将此添加到初始化程序以禁用欺骗保护:

require 'paperclip/media_type_spoof_detector'         
module Paperclip         
 class MediaTypeSpoofDetector        
    def spoofed?         
      false       
    end       
  end        
end             
Run Code Online (Sandbox Code Playgroud)

对于centOS

 module Paperclip     
 class MediaTypeSpoofDetector      
 def type_from_file_command      
  begin       
    Paperclip.run("file", "-b --mime :file", :file => @file.path)
  rescue Cocaine::CommandLineError
    ""
  end       
end      
end      
end
Run Code Online (Sandbox Code Playgroud)

来自https://github.com/thoughtbot/paperclip/issues/1429


dar*_*123 5

跳过欺骗检查是一个坏主意。因为Paperclip出于安全原因添加了它。有关详细信息,请参见本文:http : //robots.thoughtbot.com/prevent-spoofing-with-paperclip

欺骗验证将检查文件的扩展名是否匹配其mime类型。例如,txt文件的mime类型为text/plain,将其上传到Paperclip时一切正常。但是,如果您修改扩展名jpg然后上传,则验证失败,因为jpg文件的mime类型应为image/jpeg

请注意,此验证用于安全性检查,因此没有正常的方法可以跳过它。即使您使用do_not_validate_attachment_file_type它,也不会被跳过。但是对于某些文件,Paperclip无法正确识别文件-> mime类型映射。

在这种情况下,正确的方法是将内容类型映射添加到Paperclip配置。像这样:

# Add it to initializer
Paperclip.options[:content_type_mappings] = {
  pem: 'text/plain'
}
Run Code Online (Sandbox Code Playgroud)

这样,它就可以工作而不会破坏欺骗验证。如果您不知道文件的MIME类型,可以使用以下file命令:

file -b --mime-type  some_file.pdf    # -> application/pdf
Run Code Online (Sandbox Code Playgroud)