0

In my Rails web application, I have to upload audio and video files and for validating against invalid file types, I have used jquery-validation engine and I could do the same successfully. But, if I create a text file and change the extension from .txt to .mp3, e.g. test.txt to test.mp3, it will be taken as valid by jquery validation engine as the file extension is valid for an audio.

I want to check the content type also. When I opened the test.mp3 in a player, it showed me an error message Stream contains no data. I want this kind of validation to be performed in the interface. Is it possible in Rails?

I'm using,

Rails 3.2.13

Ruby 2.0.0-dev

Hope anyone can help me out. Thanks :)-

Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85

1 Answers1

2

I recommend you to check paperclip gem its a file attachment library for Active Record. This library is very straightforward to use and make validations with each content type. For example if you want to validate an Image you can by the next validation:

class User < ActiveRecord::Base
  attr_accessible :avatar
  has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

  validates_attachment :avatar, 
  :presence => true, :content_type => { :content_type => "image/jpg" },
  :size => { :in => 0..500.kilobytes }

end

Hope it helps.

Jorge Najera T
  • 1,511
  • 2
  • 20
  • 29
  • can we validate the content-type in a scenario that I have furnished in the question? – Rajesh Omanakuttan Sep 09 '13 at 06:07
  • If you really need to check the data of the file you can do it using FileMagic. Check this other question for know how to use it http://stackoverflow.com/questions/51572/determine-file-type-in-ruby You can found the gem here https://github.com/blackwinter/ruby-filemagic – Jorge Najera T Sep 09 '13 at 06:34