ruby-on-rails-3 – Paperclip验证pdfs with content_type =’application / octet-stream’

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – Paperclip验证pdfs with content_type =’application / octet-stream’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用纸夹进行文件上传.验证如下:

validates_attachment_content_type:upload,:content_type => [‘application / pdf’],
:if => Proc.new {| module_file | !module_file.upload_file_name.blank? },
:message => “必须以”.pdf“格式”

但是,我的客户今天抱怨说他无法上传pdf.调查后,我从请求头知道,提交的文件是content_type = application / octet-stream.

允许应用程序/八位字节流将允许许多类型的文件进行上传.

请建议一个解决方案来处理这个.

解决方法

像回形针似乎没有正确检测到内容类型.以下是使用自定义内容类型检测和验证(代码在模型中)来修复它的方法
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
原文链接:https://www.f2er.com/ruby/265346.html

猜你在找的Ruby相关文章