在Rails應用中使用OSS Ruby SDK只需要在Gemfile
中添加以下依賴:
gem 'aliyun-sdk', '~> 0.3.0
然後在使用OSS時引入依賴就可以了:
require 'aliyun/oss'
另外,SDK的rails/目錄下提供一些方便使用者使用的輔助代碼。
下面我們將利用SDK來實現一個簡單的OSS檔案管理工具(oss-manager),最終包含以下功能:
- 列出使用者所有的Bucket
- 列出Bucket下所有的檔案,按目錄層級列出
- 上傳檔案
- 下載檔案
1. 建立項目
先安裝Rails,然後建立一個Rails應用,oss-manager:
gem install rails
rails new oss-manager
作為一個好的習慣,使用git管理項目代碼:
cd oss-manager
git init
git add .
git commit -m "init project"
2. 添加SDK依賴
編輯oss-manager/Gemfile
,向其中加入SDK的依賴:
gem 'aliyun-sdk', '~> 0.3.0'
然後在oss-manager/
下執行:
bundle install
保存這一步所做的更改:
git add .
git commit -m "add aliyun-sdk dependency"
3. 初始化OSS Client
為了避免在項目中用到OSS Client的地方都要初始化,我們在項目中添加一個初始化檔案,方便在項目中使用OSS Client:
# 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
上面的代碼在SDK的rails/目錄下可以找到。這樣初始化後,在項目中使用OSSClient就非常方便:
buckets = OSS.client.list_buckets
其中endpoint和AccessKeyId/AccessKeySecret保存在oss-manager/conf/secrets.yml
中,例如:
development:
secret_key_base: xxxx
aliyun_oss:
endpoint: xxxx
access_key_id: aaaa
access_key_secret: bbbb
保存代碼:
git add .
git commit -m "add aliyun-sdk initializer"
4. 實現List buckets功能
首先用rails生成管理Buckets的controller:
rails g controller buckets index
這樣會在oss-manager
中生成以下檔案:
- app/controller/buckets_controller.rb Buckets相關的邏輯代碼
- app/views/buckets/index.html.erb Buckets相關的展示代碼
- app/helpers/buckets_helper.rb 一些輔助函數
首先編輯buckets_controller.rb,調用OSS Client,將list_buckets
的結果存放在@buckets
變數中:
class BucketsController < ApplicationController
def index
@buckets = OSS.client.list_buckets
end
end
然後編輯views/buckets/index.html.erb,將Bucket列表展示出來:
<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>
其中bucket_objects_path
是一個輔助函數,在app/helpers/buckets_helper.rb中:
module BucketsHelper
def bucket_objects_path(bucket_name)
"/buckets/#{bucket_name}/objects"
end
end
這樣就完成了列出所有Bucket的功能。在運行之前,我們還需要配置Rails的路由,使得我們在瀏覽器中輸入的地址能夠調用正確的邏輯。編輯config/routes.rb
,增加一條:
resources :buckets do
resources :objects
end
好了,在oss-manager/下輸入rails s
以啟動rails server,然後在瀏覽器中輸入http://localhost:3000/buckets/
就能看到Bucket列表了。
最後保存一下代碼:
git add .
git commit -m "add list buckets feature"
5. 實現List objects功能
首先生成一個管理Objects的controller:
rails g controller objects index
然後編輯app/controllers/objects_controller.rb:
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
上面的代碼首先從URL的參數中獲取Bucket名字,為了只按目錄層級顯示,我們還需要一個首碼。然後調用OSS Client的list_objects介面獲取檔案清單。注意,這裡獲取的是指定首碼下,並且以’/‘為分界的檔案。這樣做是為也按目錄層級列出檔案。請參考管理檔案
接下來編輯app/views/objects/index.html.erb:
<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>
上面的代碼將檔案按目錄結構顯示,主要邏輯是:
- 總是在第一個顯示’../‘指向上級目錄
- 對於Common prefix,顯示為目錄
- 對於Object,顯示為檔案
上面的代碼中用到了with_prefix
, remove_prefix
等一些輔助函數,它們定義在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
完成之後運行rails s
,然後在瀏覽器中輸入地址http://localhost:3000/buckets/my-bucket/objects/
就可以查看檔案清單了。
慣例保存代碼:
git add .
git commit -m "add list objects feature"
6. 下載檔案
注意到在上一步顯示檔案清單時,我們為每個檔案也添加了一個連結:
<td><%= link_to remove_prefix(object.key, @prefix),
@bucket.object_url(object.key) %></td>
其中Bucket#object_url
是一個為檔案生成臨時URL的方法,參考下載檔案
7. 上傳檔案
在Rails這種服務端應用中,使用者上傳檔案有兩種辦法:
- 使用者先將檔案上傳到Rails的伺服器上,伺服器再將檔案上傳到OSS。這樣做需要Rails伺服器作為中轉,檔案多拷貝了一遍,不是很高效。
- 伺服器為使用者生成表單和臨時憑證,使用者直接上傳檔案到OSS。
第一種方法比較簡單,與普通的上傳檔案一樣。下面我們用的是第二種方法:
首先在app/controllers/objects_controller.rb中增加一個#new
方法,用於生成上傳表單:
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
然後編輯app/views/objects/new.html.erb:
<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" />
<span>  </span>
<%= link_to 'Back', objects_path(@bucket_name, @prefix) %>
</td>
</tr>
</table>
<% end %>
其中upload_form
是SDK提供的一個方便使用者生成上傳表單的輔助函數,在SDK的代碼rails/aliyun_oss_helper.rb中。使用者需要將其拷貝到app/helpers/目錄下。完成之後運行rails s
,然後訪問http://localhost:3000/buckets/my-bucket/objects/new
就能夠上傳檔案了。
最後記得保存代碼:
git add .
git commit -m "add upload object feature"
8. 添加樣式
為了讓介面更好看一些,我們可以添加一點樣式(CSS)。
首先下載bootstrap,解壓後將bootstrap.min.css
拷貝到app/assets/stylesheets/
下。
然後在修改app/views/layouts/application.html.erb
,將yield
一行改成:
<div id="main">
<%= yield %>
</div>
這會為每個頁面添加一個id為main的<div>
,然後修改app/assets/stylesheets/application.css
,加入以下內容:
body {
text-align: center;
}
div#main {
text-align: left;
width: 1024px;
margin: 0 auto;
}
這會讓網頁的主體內容置中顯示。通過添加簡單的樣式,我們的頁面是不是更加賞心悅目了呢?
至此,一個簡單的demo就完成了。完整的demo代碼請參看 Alibaba Cloud OSS Rails Demo。