简体   繁体   中英

Ruby On Rails uploading songs to Rackspace Cloud Files container

Ok so here's the deal, I'm creating a web app and I'm adding the function to upload music to user profiles. I'm using Rackspace cloud files for storage, and I'm having a little bit of trouble completing two task. Firstly I'm having trouble writing the code to upload the file to my container. Secondly I need to generate the url of the file to store in the database. I'm very new to integrating API's so i don't have a lot of knowledge.

object = container.create_object 'filename', false
object.write file

Is this code correct for uploading the files?

Using fog directly

First of all, if you're not already using it, the officially supported Ruby library for interacting directly with Cloud Files from Ruby is fog . To start, add it to your Gemfile :

gem 'fog'

Then run bundle install to install it.

To upload a file and get its public url, using fog directly:

# 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

Using CarrierWave

However! What you're doing is a pretty common usecase in Rails, so there's a gem for it: CarrierWave . Add the following line to your Gemfile:

gem 'fog'
gem 'carrierwave'

And run bundle install to install it. Now configure CarrierWave to use Cloud Files:

# 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

Next generate an uploader :

rails g uploader Song

Now you can use the SongUploader to store and retrieve Song data. See the generated code, or the CarrierWave docs , for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM