2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Rails]さくらのオブジェクトストレージにPDF保存

Last updated at Posted at 2017-10-08

環境

CentOS 6.5
Ruby 2.3.1
rails 5.0.0

gemインストール

gem 'sakura_object_storage', git: 'https://github.com/kmamiya/sakura_object_storage_ruby.git'

コントローラに追記

共通

テーブル名_controller.rb
require 'sakura_object_storage'

アクション内で必ずインスタンスを発行する。
bucket_name → バケット名
api_key → キー名
api_secret_key → API秘密鍵

テーブル名_controller.rb
instance = SakuraObjectStorage::Storage.new( bucket_name, api_key, api_secret_key )

put_object

オブジェクトの保存には、

  • ファイル名
  • ファイル本体
  • ファイルサイズ

が必要になる。
Railsでファイル保存している場合は、フォームから入力されたパラメータ(params[:file])のままではファイル本体とファイルサイズが取れなかったので、一度ローカルファイルとして保存して、openメソッドでdataとして取り出した。

テーブル名_controller.rb
result = uploadpdf(file,file_name) #ローカルファイル保存
file = Rails.root + 'All_PDF/' + file_name
data = File.open(file, "rb") {|io| io.read}

instance.put_object(file_name,data,data.size) #オブジェクトストレージに保存

if File.exist?(Rails.root + 'All_PDF/' + file_name)
	deletepdf(file_name) #ローカルファイルを削除
end

get_object

ローカルファイルをブラウザ上に表示するときはsend_fileメソッドを使ったが、今回はローカルには保存しないので、取ってきたデータをそのままsend_dataメソッドでPDFとしてinline表示させる。

テーブル名_controller.rb
obj = instance.get_object(file_name)
send_data(
    obj,
    :type => 'application/pdf',
    :disposition => 'inline'
)

delete_object

シンプル。

テーブル名_controller.rb
instance.delete_object(file_name)

参照

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?