Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CarrierWave multiple file types validation with single uploader

How to validate the extension of uploaded file when using single uploader for multiple file type?

I am using the single model namely Asset containing the attribute file. Uploader is mounted on file attribute. Asset model having one more attribute called feature_id. feature_id refers to features like video, audio, etc.

So, how should I validate the file type with multiple extension whitelist depending upon feature_id value?

Using ruby 1.9 and rails 3.2.11

Any help will be greatly appreciated.

like image 869
maximus ツ Avatar asked Dec 12 '22 18:12

maximus ツ


2 Answers

Although the answer has been accepted but I've got a better way for this. Try this code.

class MyUploader < CarrierWave::Uploader::Base
  def extension_white_list
    if model.feature_id == 1
      %w(jpg jpeg gif png)
    elsif model.feature_id == 2
      %w(pdf doc docx xls xlsx)
    elsif model.feature_id == 3
      %w(mp3 wav wma ogg)
    end
  end
end

feature_id == 1 means you want to allow just picture uploads, feature_id == 2 means that only documents will be allowed to be uploaded and feature_id == 3 will allow you to upload only audio files.

Hopefully it answers the question. You can add more checks for other types of files.

like image 101
KULKING Avatar answered Apr 23 '23 11:04

KULKING


Define your white list in your uploader as shown in the docs for carrierwave.

class MyUploader < CarrierWave::Uploader::Base
  def extension_white_list
    %w(jpg jpeg gif png)
  end
end
like image 25
Polygon Pusher Avatar answered Apr 23 '23 11:04

Polygon Pusher