简体   繁体   English

Ruby On Rails将歌曲上传到Rackspace Cloud Files容器

[英]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. 好的,这是交易,我正在创建一个Web应用程序,并添加了将音乐上传到用户个人资料的功能。 I'm using Rackspace cloud files for storage, and I'm having a little bit of trouble completing two task. 我正在使用Rackspace云文件进行存储,并且在完成两项任务时遇到了一些麻烦。 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. 其次,我需要生成文件的URL以存储在数据库中。 I'm very new to integrating API's so i don't have a lot of knowledge. 我是集成API的新手,所以我没有很多知识。

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 . 首先,如果您尚未使用它,那么与Ruby中的Cloud Files直接交互的官方支持的Ruby库就是fog To start, add it to your Gemfile : 首先,将其添加到您的Gemfile

gem 'fog'

Then run bundle install to install it. 然后运行bundle install进行安装。

To upload a file and get its public url, using fog directly: 要上传文件并获取其公共网址,请直接使用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

Using CarrierWave 使用CarrierWave

However! 然而! What you're doing is a pretty common usecase in Rails, so there's a gem for it: CarrierWave . 您正在做的是Rails中一个非常常见的用例,因此有一个瑰宝: CarrierWave Add the following line to your Gemfile: 将以下行添加到您的Gemfile中:

gem 'fog'
gem 'carrierwave'

And run bundle install to install it. 并运行bundle install进行安装。 Now configure CarrierWave to use Cloud Files: 现在将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

Next generate an uploader : 接下来生成一个上传器

rails g uploader Song

Now you can use the SongUploader to store and retrieve Song data. 现在,您可以使用SongUploader来存储和检索Song数据。 See the generated code, or the CarrierWave docs , for more details. 有关更多详细信息,请参见生成的代码或CarrierWave docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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