Checking Multiple CarrierWave File Types with One Loader
How can I check the extension of a downloaded file when using one downloader for multiple file types?
I am using a single model, namely Asset, which contains an attribute file. The uploader is set to a file attribute. An asset model with another attribute called feature_id. feature_id refers to features like video, audio, etc.
So how am I supposed to validate the file type with a large whitelist of additions based on the feature_id value?
Using ruby 1.9 and rails 3.2.11
Any help would be greatly appreciated.
source to share
I came across the same option:
In Asset.rb Confirm filename format
validates :asset_file,
format:{
with: %r{\.(pdf|doc|png)$}i, message: "Wrong file format"
}
Use a regular expression to check the filename:
You can play with regex here: http://rubular.com/r/Z3roRDDXAf
Hope this helps!
source to share
Although the answer is accepted, but I have a better way to do 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 only allow uploading images, feature_id == 2
means only documents will be uploaded, and feature_id == 3
will only allow you to upload audio files.
I hope he answers the question. You can add additional checks for other file types.
source to share