Paperclip- validate pdfs with content_type='application/octet-stream'

前端 未结 3 1039
走了就别回头了
走了就别回头了 2020-12-28 09:58

I was using paperclip for file upload. with validations as below:

validates_attachment_content_type :upload, :content_type=>[\'application/pdf\

3条回答
  •  庸人自扰
    2020-12-28 10:54

    Seems like paperclip doesn't detect content type correctly. Here is how I was able to fix it using custom content-type detection and validation (code in model):

    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
    

提交回复
热议问题