我在Google云端存储(GCS)中有一个包含输入字段和上传图片按钮的表单。如果我输入的是无效值,则此表格将呈现。渲染图像后遗漏。我使用Carrierwave和Fog / Google。我试图添加缓存但它没有帮助。图像保存在GCS中,image_cache不保存,但是缓存文件的URL存在于html代码中。 者:
class PhotoUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
process resize_to_fit: [500, 500]
# Choose what kind of storage to use for this uploader:
# storage :file
if Rails.env.development?
#storage :file
def store_dir
Rails.root + "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def cache_dir
Rails.root + "uploads/tmp/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
else
#storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def cache_dir
"uploads/tmp/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
ActionController::Base.helpers.asset_path([version_name, 'form-default.png'].compact.join('_'))
end
初始化器:
require 'carrierwave/storage/file'
require 'carrierwave/storage/fog'
CarrierWave.configure do |config|
if not Rails.env.development?
config.storage = :fog
config.fog_provider = 'fog/google'
config.fog_credentials = {
provider: 'Google',
google_storage_access_key_id: ENV['GSASAK'],
google_storage_secret_access_key: ENV['GSSAK'],
persistent: false
}
config.fog_directory = 'my-bucket'
config.asset_host = 'https://storage.googleapis.com/my-bucket'
config.fog_public = true
else
config.storage = :file
end
end
查看:
<% if @form.photo? %>
<div class="photo-new"><img src= <%= @form.photo_url %> id="output"/></div>
<% else %>
<div class="photo-new"><img id="output"/></div>
<% end %>
<div class="container" style="background-color: #e0e0e0" title="Upload photo of your product">
<label for="upload" class="uploadButton">UPLOAD PHOTO</label>
<%= f.hidden_field :photo_cache %>
<%= f.file_field :photo, id: "upload", onchange: "loadFile(event)" %>
型号:
class Form < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
控制器(许可证参数):
def form_params
params.require(:form).permit!
end