【问题标题】:Paperclip- validate pdfs with content_type='application/octet-stream'Paperclip- 使用 content_type='application/octet-stream' 验证 pdf
【发布时间】:2011-10-18 05:33:00
【问题描述】:

我使用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 将允许上传多种类型的文件。

请提出解决方案来解决这个问题。

【问题讨论】:

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


    【解决方案1】:

    似乎回形针无法正确检测内容类型。以下是我如何使用自定义内容类型检测和验证(模型中的代码)来修复它:

    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
    

    【讨论】:

      【解决方案2】:

      基于上述,我最终得到了与 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
      

      【讨论】:

        【解决方案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 类型。

        【讨论】:

        • 我发现为了避免处理具有不正确 MIME 类型的文件,我必须将其用作 before_file_post_process 方法。
        猜你喜欢
        • 1970-01-01
        • 2014-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-28
        • 2019-01-21
        • 1970-01-01
        相关资源
        最近更新 更多