All Products
Search
Document Center

Object Storage Service:Rails application (Ruby SDK)

Last Updated:Nov 29, 2025

This topic describes how to use Object Storage Service (OSS) SDK for Ruby in Rails applications to list buckets, upload objects, and download objects.

Preparations

To use the OSS SDK for Ruby in a Rails application, add the following dependency to the Gemfile file.

gem 'aliyun-sdk', '~> 0.3.0
            

Add the following dependency when you use OSS SDK for Ruby:

require 'aliyun/oss'
            

Integration with Rails

You can perform the following steps to integrate OSS SDK for Ruby with Rails:

  1. Create a project.

    1. Install Rails and create a Rails application named oss-manager.

      gem install rails
      rails new oss-manager
                                  
      Note

      In this example, the oss-manager application is a management tool for OSS objects. It can list all buckets, list objects in a bucket by directory, upload objects, and download objects.

    2. Use git to manage the project code.

      cd oss-manager
      git init
      git add .
      git commit -m "init project"
                                  
  2. Add the SDK dependency.

    1. Edit oss-manager/Gemfile to add the SDK dependency.

      gem 'aliyun-sdk', '~> 0.3.0'
                                  
    2. In the oss-manager/ directory, run bundle install.

    3. Save the changes.

      git add .
      git commit -m "add aliyun-sdk dependency"
                                  

Initialize an OSSClient instance

To avoid initialization each time you use an OSSClient instance in the project, we recommend that you create an initialization file in the project.

# oss-manager/config/initializers/aliyun_oss_init.rb
require 'aliyun/oss'

module OSS
  def self.client
    unless @client
      Aliyun::Common::Logging.set_log_file('./log/oss_sdk.log')

      @client = Aliyun::OSS::Client.new(
        endpoint:
          Rails.application.secrets.aliyun_oss['endpoint'],
        access_key_id:
          Rails.application.secrets.aliyun_oss['access_key_id'],
        access_key_secret:
          Rails.application.secrets.aliyun_oss['access_key_secret']
      )
    end

    @client
  end
end            

The preceding code is stored in the rails/ directory of the installation path of OSS SDK for Ruby. You can use the OSSClient instance in the project after initialization.

buckets = OSS.client.list_buckets            

The endpoint, access_key_id, and access_key_secret values are saved in the oss-manager/conf/secrets.yml file.

development:
  secret_key_base: xxxx
  aliyun_oss:
    endpoint: xxxx
    access_key_id: aaaa
    access_key_secret: bbbb           

Save the changes.

git add .
git commit -m "add aliyun-sdk initializer"            

List all buckets

You can perform the following steps to list all buckets:

  1. Use Rails to generate the controller to manage buckets.

    rails g controller buckets index
                        
  2. The following files are generated in the oss-manager folder.

    • app/controller/buckets_controller.rb: contains the logical code related to buckets.

    • app/views/buckets/index.html.erb: contains the code used to display the content related to buckets.

    • app/helpers/buckets_helper.rb: defines the auxiliary functions.

  3. Edit `buckets_controller.rb`. Call the OSS client and save the result of the list_buckets operation to the @buckets variable.

    class BucketsController < ApplicationController
      def index
        @buckets = OSS.client.list_buckets
      end
    end
  4. Modify the views/buckets/index.html.erb file to list the buckets.

    <h1>Buckets</h1>
    <table class="table table-striped">
      <tr>
        <th>Name</th>
        <th>Location</th>
        <th>CreationTime</th>
      </tr>
    
      <% @buckets.each do |bucket| %>
      <tr>
        <td><%= link_to bucket.name, bucket_objects_path(bucket.name) %></td>
        <td><%= bucket.location %></td>
        <td><%= bucket.creation_time.localtime.to_s %></td>
      </tr>
      <% end %>
    </table>
                        
  5. In `app/helpers/buckets_helper.rb`, define the bucket_objects_path helper function.

    module BucketsHelper
      def bucket_objects_path(bucket_name)
        "/buckets/#{bucket_name}/objects"
      end
    end
                        

    After you complete the preceding steps, you can list all buckets.

    You also need to configure Rails routing so that the address entered in the browser calls the correct logic. Edit config/routes.rb and add the following content.

    resources :buckets do
      resources :objects
    end
                        

    In the oss-manager/ directory, run rails s to start the Rails server. Then, navigate to http://localhost:3000/buckets/ in your browser to view the bucket list.

  6. Save the changes.

    git add .
    git commit -m "add list buckets feature"
                        

List all objects in a bucket by directory

You can perform the following steps to list all objects in a bucket by directory:

  1. Generate a controller to manage objects.

    rails g controller objects index
                        
  2. Modify the app/controllers/objects_controller.rb file.

    class ObjectsController < ApplicationController
      def index
        @bucket_name = params[:bucket_id]
        @prefix = params[:prefix]
        @bucket = OSS.client.get_bucket(@bucket_name)
        @objects = @bucket.list_objects(:prefix => @prefix, :delimiter => '/')
      end
    end
                        

    You can obtain the bucket name from the parameters in the URL. Add a prefix to list objects by directory and call the list_object operation of the OSSClient instance to obtain the object list.

    Note

    In this example, objects whose names contain the specified prefix and a forward slash (/) as a delimiter are obtained. For more information, see Overview.

  3. Modify the app/views/objects/index.html.erb file.

    <h1>Objects in <%= @bucket_name %></h1>
    <p> <%= link_to 'Upload file', new_object_path(@bucket_name, @prefix) %></p>
    <table class="table table-striped">
      <tr>
        <th>Key</th>
        <th>Type</th>
        <th>Size</th>
        <th>LastModified</th>
      </tr>
    
      <tr>
        <td><%= link_to '../', with_prefix(upper_dir(@prefix)) %></td>
        <td>Directory</td>
        <td>N/A</td>
        <td>N/A</td>
      </tr>
    
      <% @objects.each do |object| %>
      <tr>
        <% if object.is_a?(Aliyun::OSS::Object) %>
        <td><%= link_to remove_prefix(object.key, @prefix),
                @bucket.object_url(object.key) %></td>
        <td><%= object.type %></td>
        <td><%= number_to_human_size(object.size) %></td>
        <td><%= object.last_modified.localtime.to_s %></td>
        <% else  %>
        <td><%= link_to remove_prefix(object, @prefix), with_prefix(object) %></td>
        <td>Directory</td>
        <td>N/A</td>
        <td>N/A</td>
        <% end  %>
      </tr>
      <% end %>
    </table>
                        

    Objects are listed by directory based on the following logic:

    1. '../' always refers to the parent directory.

    2. Common prefixes are listed as directories.

    3. Objects are displayed as files.

    The preceding code uses helper functions such as with_prefix and remove_prefix. These helper functions are defined in `app/helpers/objects_helper.rb`.

    module ObjectsHelper
      def with_prefix(prefix)
        "?prefix=#{prefix}"
      end
    
      def remove_prefix(key, prefix)
        key.sub(/^#{prefix}/, '')
      end
    
      def upper_dir(dir)
        dir.sub(/[^\/]+\/$/, '') if dir
      end
    
      def new_object_path(bucket_name, prefix = nil)
        "/buckets/#{bucket_name}/objects/new/#{with_prefix(prefix)}"
      end
    
      def objects_path(bucket_name, prefix = nil)
        "/buckets/#{bucket_name}/objects/#{with_prefix(prefix)}"
      end
    end
                        
  4. When you are finished, run rails s. Then, navigate to http://localhost:3000/buckets/my-bucket/objects/ in your browser to view the file list.

  5. Save the changes.

    git add .
    git commit -m "add list objects feature"                    

Download objects

In the steps in the preceding section, URLs are added to the objects. You can use the URL of an object to download the object.

<td><%= link_to remove_prefix(object.key, @prefix),
        @bucket.object_url(object.key) %></td>               

You can also use bucket.object_url to generate a temporary URL for a file. For more information, see Download files.

Upload objects

To upload objects in Rails applications on the server, you can use the following methods:

  • Upload objects in a similar manner as normal upload. You need to upload an object to the Rails server. Then, the Rails server uploads the object to OSS.

  • Upload objects using the forms and temporary credentials generated by the server.

    1. In `app/controllers/objects_controller.rb`, add the #new method to generate the upload form.

      def new
        @bucket_name = params[:bucket_id]
        @prefix = params[:prefix]
        @bucket = OSS.client.get_bucket(@bucket_name)
        @options = {
          :prefix => @prefix,
          :redirect => 'http://localhost:3000/buckets/'
        }
      end
                                      
    2. Modify the app/views/objects/new.html.erb file.

      <h2>Upload object</h2>
      
      <%= upload_form(@bucket, @options) do %>
        <table class="table table-striped">
          <tr>
            <td><label>Bucket:</label></td>
            <td><%= @bucket.name  %></td>
          </tr>
          <tr>
            <td><label>Prefix:</label></td>
            <td><%= @prefix  %></td>
          </tr>
      
          <tr>
            <td><label>Select file:</label></td>
            <td><input type="file" name="file" style="display:inline" /></td>
          </tr>
      
          <tr>
            <td colspan="2">
              <input type="submit" class="btn btn-default" value="Upload" />
              &nbsp;&nbsp
      Note

      upload_form is a helper function provided by the SDK that you can use to easily generate an upload form. This helper function is stored in `rails/aliyun_oss_helper.rb`. Copy it to the `app/helpers/` directory. After that, run rails s and navigate to http://localhost:3000/buckets/my-bucket/objects/new to upload files to OSS.

    3. Save the changes.

      git add .
      git commit -m "add upload object feature"                               

Add styles

You can perform the following steps to add styles to the interface of the Rails application:

  1. Download Bootstrap. After you decompress the package, copy the bootstrap.min.css file to the app/assets/stylesheets/ directory.

  2. Modify app/views/layouts/application.html.erb and replace the yield line with the following code.

      <div id="main">
        <%= yield %>
      </div>
                            
  3. For each page, add a <div> with the ID `main`. Then, modify app/assets/stylesheets/application.css and add the following content.

    body {
        text-align: center;
    }
    
    div#main {
        text-align: left;
        width: 1024px;
        margin: 0 auto;
    }
                            

For the complete demo code, visit OSS Rails Demo.