簡體   English   中英

使用carrierwave將圖像上傳到谷歌雲存儲,文件名最終被保存,而不是桶中圖像的公共鏈接

[英]Using carrierwave to upload images to google cloud storage, the file name ends up being saved and not the public link to the image in the bucket

我正在嘗試使用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雲存儲公共鏈接。

我使用了載波文檔這篇文章 ,以及谷歌雲平台的這個視頻來獲得我現在擁有的東西。 我錯過了什么?

更新

添加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

要將鏈接設置為public,請在配置文件中檢查此配置:

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM