Paperclip-使用content_type ='application / octet-stream'验证pdfs

时间:2011-08-02 12:29:03

标签: ruby-on-rails-3 paperclip paperclip-validation

我使用paperclip进行文件上传。验证如下:

validates_attachment_content_type :upload, :content_type=>['application/pdf'], :if => Proc.new { |module_file| !module_file.upload_file_name.blank? }, :message => "must be in '.pdf' format"

但是,我的客户今天抱怨他无法上传pdf。经过调查,我从请求标题中了解到,提交的文件有content_type=application/octet-stream

允许application/octet-stream将允许上传多种类型的文件。

请建议一个解决方案来解决这个问题。

3 个答案:

答案 0 :(得分:7)

似乎paperclip无法正确检测内容类型。以下是我能够使用自定义内容类型检测和验证(模型中的代码)修复它的方法:

VALID_CONTENT_TYPES = ["application/zip", "application/x-zip", "application/x-zip-compressed", "application/pdf", "application/x-pdf"]

before_validation(:on => :create) do |file|
  if file.media_content_type == 'application/octet-stream'
    mime_type = MIME::Types.type_for(file.media_file_name)    
    file.media_content_type = mime_type.first.content_type if mime_type.first
  end
end

validate :attachment_content_type

def attachment_content_type
  errors.add(:media, "type is not allowed") unless VALID_CONTENT_TYPES.include?(self.media_content_type)
end

答案 1 :(得分:5)

基于以上所述,我最终得到的内容与PaperClip 4.2和Rails 4兼容:

before_post_process on: :create do    
  if media_content_type == 'application/octet-stream'
    mime_type = MIME::Types.type_for(media_file_name) 
    self.media_content_type = mime_type.first.to_s if mime_type.first  
  end
end

答案 2 :(得分:3)

对于回形针3.3和Rails 3,我的做法有点不同

before_validation on: :create do   
  if media_content_type == 'application/octet-stream'
    mime_type = MIME::Types.type_for(media_file_name) 
    self.media_content_type = mime_type.first if mime_type.first  
  end
end

validates_attachment :media, content_type: { content_type: VALID_CONTENT_TYPES } 

顺便说一下,我需要这样做,因为使用attach_file测试Capybara和phantom js并没有为某些文件生成正确的mime类型。