Skip to content

Instantly share code, notes, and snippets.

@a-chernykh
Created August 9, 2011 14:28
Show Gist options
  • Save a-chernykh/1134188 to your computer and use it in GitHub Desktop.
Save a-chernykh/1134188 to your computer and use it in GitHub Desktop.
CarrierWave extension-aware remote file downloading
class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def extension_white_list
model.skip_avatar_extension_check ? nil : %w(jpg jpeg gif png bmp)
end
end
class Profile < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
attr_accessor :skip_avatar_extension_check
def file_avatar_url=(url)
begin
self.skip_avatar_extension_check = true
avatar.download!(url)
ensure
self.skip_avatar_extension_check = false
end
path = avatar.path
ext = File.extname(path)
logger.debug "Downloaded file extension - #{ext}"
if ext.blank? && ext = detect_extension(path)
logger.debug "Detected extension for avatar - #{ext}"
path = path + ".#{ext}"
FileUtils.mv(avatar.path, path)
avatar.remove!
self.avatar = File.open(path)
end
avatar.send(:check_whitelist!, CarrierWave::SanitizedFile.new(File.open(path)))
avatar.store!
save!
end
protected
def detect_extension(file_name)
mime_type = %x(file --mime-type #{file_name}|cut -f2 -d' ').gsub("\n", "")
case mime_type
when 'image/jpeg'
'jpg'
when 'image/jpg'
'jpg'
when 'image/png'
'png'
when 'image/gif'
'gif'
end
end
end
@rezwyi
Copy link

rezwyi commented Jul 22, 2013

A little simplier:

mime_type = %x(file --mime-type -b #{file_name}).gsub("\n", '')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment