我正在尝试使用carrierwave gem从我的rails 4.2应用程序实现图像上传到谷歌云存储。每当我去上传图像时,它都会很好地上传到存储桶,但它作为原始图像名称保存在数据库中,例如image.png
,而不是图片的Google云存储公共链接,例如https://storage.googleapis.com/project/bucket/image.png
不太清楚从这里需要做什么才能让它从存储桶中保存公共链接而不仅仅是文件名。
carrierwave.rb文件
CarrierWave.configure do |config|
config.fog_credentials = {
provider: 'Google',
google_storage_access_key_id: 'key',
google_storage_secret_access_key: 'secret key'
}
config.fog_directory = 'bucket-name'
end
上传/ check_item_value_image_uploader.rb
class CheckItemValueImageUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
# include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
#storage :file
storage :fog
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"check-item-value-images/#{model.id}"
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
end
相关宝石
gem 'gcloud'
gem "fog"
gem 'google-api-client', '~> 0.8.6'
gem "mime-types"
check_category_item_value模型
mount_uploader :value, CheckItemValueImageUploader
check_category_item_value更新方法
if @check_category_item_value.save
flash[:success] = "Successfully updated"
redirect_to category_items_edit_path(@guide, @category, @category_item)
else
render 'category_items/edit'
end
编辑表格
<%= form_for(@check_category_item_value) do |f| %>
<%= f.file_field :value, :value => item_key.value, accept: "image/jpeg, image/jpg, image/gif, image/png" %>
<%= f.submit "Submit" %><hr>
<% end %>
表单工作正常,但保存的值是原始图片名称,而不是图片的Google云端存储公共链接。
我使用谷歌云平台的carrierwave docs,this post和this video来获取我现在拥有的内容。我错过了什么?
更新
添加config.fog_public = true
无效
CarrierWave.configure do |config|
config.fog_credentials = {
provider: 'Google',
google_storage_access_key_id: 'key',
google_storage_secret_access_key: 'secret key'
}
config.fog_public = true
config.fog_directory = 'bucket-name'
end
答案 0 :(得分:1)
要将链接设置为公开,请在配置文件中检查此配置:
# You may set it false now
config.fog_public = true
对于文件名,您可以在CheckItemValueImageUploader
中覆盖,这是一个示例:
class CheckItemValueImageUploader < CarrierWave::Uploader::Base
def filename
"#{model.id}-#{original_filename}.#{file.extension}" if original_filename.present?
end
end