我正在使用纸夹进行文件上传.验证如下:
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