4
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 1 year has passed since last update.

ElixirでS3にファイルアップロード/ダウンロード

Last updated at Posted at 2023-03-16

パッケージ

インストール

mix project の場合

mix.exs
  defp deps do
    [
      {:aws, "~> 0.13"}
    ]
  end

Livebook の場合

aws_s3.livemd
Mix.install(
  [
    {:aws, "~> 0.13"}
  ]
)

Config設定

# AWSにアクセスするためのパラメータを指定(以下は環境変数で指定する例)
access_key = System.get_env("AWS_ACCESS_KEY_ID")
secret_key = System.get_env("AWS_SECRET_ACCESS_KEY")
region = System.get_env("AWS_REGION")

# AWS.Clientを作成
client = AWS.Client.create(access_key, secret_key, region)

アップロード (s3:PutObject)

bucket = "your_bucket_name"
key = "elixir.txt"

content = "Elixir - S3"
md5 = :crypto.hash(:md5, content) |> Base.encode64()

AWS.S3.put_object(client, bucket, key, %{"Body" => content, "ContentMD5" => md5})
  • md5
    • アップロードしたファイルの破損チェックをしてくれる
    • 指定しなくてもアップロード可能

ダウンロード (s3:GetObject)

download_content =
  AWS.S3.get_object(client, bucket, key)
  |> elem(2)
  |> Map.get(:body)

content === download_content # true
4
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
4
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?