Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

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.

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

Please suggest a solution to deal with this.

like image 422
Pravin Avatar asked Aug 02 '11 12:08

Pravin


1 Answers

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
like image 77
Alienatix Avatar answered Sep 27 '22 01:09

Alienatix