Last active
October 10, 2016 12:26
-
-
Save radzserg/e1188230e274642c9981c2a0882e461a to your computer and use it in GitHub Desktop.
AWS S3 upload manager /lib/myapp/upload_manager/s3.ex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule App.UploadManager.S3 do | |
@behaviour App.UploadManager.Behavior | |
@config Application.get_env(:App, :file_manager)[:s3] | |
alias ExAws.S3 | |
@doc """ | |
Check if file exists on S3 bucket | |
""" | |
def exists?(key) do | |
case S3.head_object(@config[:bucket], key) |> ExAws.request do | |
{:ok, _body} -> :ok | |
{:error, error} -> {:error, error} | |
end | |
end | |
@doc """ | |
Save file to s3 bucket | |
""" | |
def save_from_file!(source_file, key, opts \\ %{}) do | |
opts = if (Map.get(opts, :acl) == nil), do: Map.put(opts, :acl, :public_read) | |
source_file = File.read!(source_file) | |
{:ok, response} = S3.put_object(@config[:bucket], key, source_file, opts) |> ExAws.request | |
case response.status_code do | |
200 -> :ok | |
_ -> {:error, response.body} | |
end | |
end | |
def save_from_content!(source, key, opts \\ %{}) do | |
opts = if (Map.get(opts, :acl) == nil), do: Map.put(opts, :acl, :public_read) | |
{:ok, response} = S3.put_object(@config[:bucket], key, source, opts) |> ExAws.request | |
case response.status_code do | |
200 -> :ok | |
_ -> {:error, response.body} | |
end | |
end | |
@doc """ | |
Delete file from S3 | |
""" | |
def delete!(key) do | |
{:ok, response} = S3.delete_object(@config[:bucket], key) |> ExAws.request | |
case response.status_code do | |
204 -> :ok | |
_ -> {:error, response.body} | |
end | |
end | |
@doc """ | |
return URL for file | |
""" | |
def url(key) do | |
# todo add ability to return URL with expired param | |
bucket = @config[:bucket] | |
bucket_host = Application.get_env(:ex_aws, :s3) | |
bucket_host = bucket_host[:host] | |
"https://#{bucket_host}/#{bucket}/#{key}" | |
end | |
@doc """ | |
Saves object to local file | |
""" | |
def save_to_local_file!(key, local_path) do | |
{:ok, response} = S3.get_object(@config[:bucket], key) |> ExAws.request | |
case response.status_code do | |
200 -> | |
File.write!(local_path, response.body) | |
{:error, error} -> {:error, error} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment