Rajesh Omanakuttan
Rajesh Omanakuttan

Reputation: 6918

How can we restrict file uploads with valid file type but invalid content-type - Rails

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 :)-

Upvotes: 0

Views: 2256

Answers (1)

Jorge Najera T
Jorge Najera T

Reputation: 1551

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.

Upvotes: 2

Related Questions