Paperclip不支持.doc文件

在rails 4.0.2中,我使用paperclip gem上传文件。 但它不支持.doc文件。 在文件上传字段下方,它显示错误消息“具有与其内容不匹配的扩展名”

在模型中,检查内容类型的validation如下:

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'] 

现在使用的gem

 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) 

我该如何解决这个问题?

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

 require 'paperclip/media_type_spoof_detector' module Paperclip class MediaTypeSpoofDetector def spoofed? false end end end 

对于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 

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

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

欺骗validation检查文件的扩展名是否与其mime类型匹配。 例如, txt文件的mime类型是text/plain ,当你将它上传到Paperclip时,一切都很顺利。 但是如果你将扩展名修改为jpg然后上传它,则validation失败,因为jpg文件的mime类型应该是image/jpeg

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

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

 # Add it to initializer Paperclip.options[:content_type_mappings] = { pem: 'text/plain' } 

通过这种方式,它可以在不破坏欺骗validation的情况下工作 如果您不知道文件的mime类型,可以使用file命令:

 file -b --mime-type some_file.pdf # -> application/pdf 

服务器日志中的错误意味着您的OS file命令无法获取.doc文件的MIME类型。 使用ubuntu 12.04时会发生这种情况。

为了解决这个问题,我稍微修改了MediaTypeSpoofDetector以使用mimetype如果file --mime不起作用。

 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 -- file_type = '' begin file_type = Paperclip.run('file', '-b --mime-type :file', file: @file.path) rescue Cocaine::CommandLineError file_type = '' end if file_type == '' begin file_type = Paperclip.run('mimetype', '-b :file', file: @file.path) rescue Cocaine::CommandLineError file_type = '' end end file_type end end end 

您可以使用do_not_validate_attachment_file_type :file授权所有内容类型

您可以使用has_attached_file :file,启用欺骗has_attached_file :file,

 class Upload #validate_media_type == false means "authorize spoofing" has_attached_file :file, validate_media_type: false #authorize all content types do_not_validate_attachment_file_type :file_if_content_type_missing end 

尝试将do_not_validate_attachment_file_type :documentvalidation放入模型中。