17
7

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 S3へファイルアップロード・ダウンロード

Last updated at Posted at 2019-02-13

前提

  • AWSの認証設定済。

詳細

gemインストール

Gemfile

gem 'aws-sdk'

操作

### ファイルアップロード

  • parms[:file]でファイル受け取り
  def upload
   region = 'XXXX'
    bucket = "#{bucket_name}" # S3バケット名
    key = "#{key}" #S3のファイル名
    client = Aws::S3::Client.new(region: region)

    upload_file = params[:file]

    client.put_object(bucket: bucket, key: key, body: upload_file.read) 
   end

ファイルダウンロード

  def download
   region = 'XXX'
    bucket = "#{bucket_name}" # S3バケット名
    key = "#{key}" #S3のファイル名

    client = Aws::S3::Client.new(region: region)
    data = client.get_object(:bucket => bucket, :key => key).body
    file_name = "#{file_name}" #ダウンロード時ファイル名
    type = 'xxx' # ファイルの型 csvの場合 'text/csv'

    send_data data.read, filename: file_name, disposition: 'attachment',  type: type
  end

備考

  • rails初心者です。アウトプット練習で書いてみました。
  • バリデーション等は考慮外。
17
7
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
17
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?