I succeed in uploading an image file to S3 using the carrierwave and fog gems, but I don't know how to remove it.
My intentions are as follows. A user uploads a image file to the User's "sumnail" attribute. The user wants to change the image. The system will remove the old file and then upload the new image. How can I accomplish this?
My uploader name is Imgs. Here is my code:
app/uploaders/imgs_uploader.rb
# encoding: utf-8
class ImgsUploader < CarrierWave::Uploader::Base
# Choose what kind of storage to use for this uploader:
# storage :file
storage :fog
def store_dir
"uploads/"
end
def extension_white_list
%w(jpg jpeg gif png)
end
def filename
Time.now.to_i.to_s + [*('a'..'z')].sample(8).join + "." + file.extension if original_filename
end
end
app/controllers/home_controller.rb
def sumnailUpload
u = User.find(current_user.id)
unless u.sumnail.empty?
# I think remove old image code here.
end
file = params[:sumnail]
uploader = ImgsUploader.new
uploader.store!(file)
u.sumnail = uploader.url
u.save
redirect_to "/home/index"
end
config/initailzers/aws.rb
CarrierWave.configure do |config|
#config.fog_provider = 'fog/aws' # required
config.fog_credentials = {
provider: 'AWS',
aws_access_key_id: ENV['ACCESS_KEY_ID'],
aws_secret_access_key: ENV['SECRET_ACCESS_KEY'],
region: 'ap-northeast-2',
endpoint: 'https://s3.ap-northeast-2.amazonaws.com'
}
config.fog_directory = 'filefile'
config.fog_public = true
config.fog_attributes = {}
end
=================================================================
17.2.6 I solved like this
app/models/user.rb require 'carrierwave/orm/activerecord' class User < ActiveRecord::Base mount_uploader :avatar, AvatarUploader ... end
app/uploaders/imgs_uploader.rb class ImgsUploader < CarrierWave::Uploader::Base
storage :fog
...
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
...
def filename
# "something.jpg" if original_filename
"u_#{model.id}." + file.extension if original_filename
end
end
then, I used like this.
one_user.avatar.store!("")