回形针-使用content_type ='application/octet-stream'验证pdf [英] Paperclip- validate pdfs with content_type='application/octet-stream'

查看:554
本文介绍了回形针-使用content_type ='application/octet-stream'验证pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用paperclip进行文件上传.验证如下:

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

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"

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.

But, my client complained today that he is not able to upload pdf. After investigating I come to know from request headers is that the file being submitted had content_type=application/octet-stream.

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

Allowing application/octet-stream will allow many type of files for upload.

请提出解决方案.

推荐答案

似乎回形针无法正确检测内容类型.这是我能够使用自定义内容类型检测和验证(模型中的代码)修复它的方式:

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

这篇关于回形针-使用content_type ='application/octet-stream'验证pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆