[英]Ruby On Rails uploading songs to Rackspace Cloud Files container
好的,這是交易,我正在創建一個Web應用程序,並添加了將音樂上傳到用戶個人資料的功能。 我正在使用Rackspace雲文件進行存儲,並且在完成兩項任務時遇到了一些麻煩。 首先,我在編寫代碼以將文件上傳到我的容器時遇到麻煩。 其次,我需要生成文件的URL以存儲在數據庫中。 我是集成API的新手,所以我沒有很多知識。
object = container.create_object 'filename', false
object.write file
此代碼是否正確上傳文件?
首先,如果您尚未使用它,那么與Ruby中的Cloud Files直接交互的官方支持的Ruby庫就是fog 。 首先,將其添加到您的Gemfile
:
gem 'fog'
然后運行bundle install
進行安裝。
要上傳文件並獲取其公共網址,請直接使用fog:
# Use your Rackspace API key, not your password; you can find your API key by logging
# in to the control panel, clicking on your name in the top-right, and choosing
# "account settings".
service = Fog::Storage.new(
provider: 'rackspace',
rackspace_username: ENV['RACKSPACE_USERNAME'],
rackspace_api_key: ENV['RACKSPACE_API_KEY']
)
dir = service.directories.create key: 'directory-name', public: true
files_to_upload.each do |path|
file = dir.files.create key: File.basename(path), body: File.open(path, 'r')
puts "public URL for #{file} is #{file.public_url}"
end
然而! 您正在做的是Rails中一個非常常見的用例,因此有一個瑰寶: CarrierWave 。 將以下行添加到您的Gemfile中:
gem 'fog'
gem 'carrierwave'
並運行bundle install
進行安裝。 現在將CarrierWave配置為使用雲文件:
# config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'rackspace',
:rackspace_username => 'xxxxxx',
:rackspace_api_key => 'yyyyyy'
}
config.fog_directory = 'name_of_directory'
end
接下來生成一個上傳器 :
rails g uploader Song
現在,您可以使用SongUploader
來存儲和檢索Song數據。 有關更多詳細信息,請參見生成的代碼或CarrierWave docs 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.