upload v0.2.0 Upload

An opinionated file uploader.

Link to this section Summary

Functions

Get the adapter from config

Cast a file path to an Upload

Converts a filename to a unique key

Gets the extension from a filename

Get the URL for a given key. It will behave differently based on the adapter you’re using

Transfer the file to where it will be stored

Link to this section Types

Link to this type t()
t() :: %Upload{
  filename: String.t(),
  key: String.t(),
  path: String.t(),
  status: term()
}
Link to this type transferred()
transferred() :: %Upload{
  filename: String.t(),
  key: String.t(),
  path: String.t(),
  status: :transferred
}
Link to this type uploadable()
uploadable() :: Plug.Upload.t() | Upload.t()
Link to this type uploadable_path()
uploadable_path() :: String.t() | Upload.t()

Link to this section Functions

Get the adapter from config.

Link to this function cast(uploadable, opts \\ [])
cast(uploadable(), list()) :: {:ok, Upload.t()} | :error

Converts a Plug.Upload to an Upload.

Examples

iex> Upload.cast(%Plug.Upload{path: "/path/to/foo.png", filename: "foo.png"})
{:ok, %Upload{path: "/path/to/foo.png", filename: "foo.png", key: "123456.png"}}

iex> Upload.cast(100)
:error
Link to this function cast_path(path, opts \\ [])
cast_path(uploadable_path(), list()) :: {:ok, Upload.t()} | :error

Cast a file path to an Upload.

Warning: Do not use cast_path with unsanitized user input.

Examples

iex> Upload.cast_path("/path/to/foo.png")
{:ok, %Upload{path: "/path/to/foo.png", filename: "foo.png", key: "123456.png"}}

iex> Upload.cast_path(100)
:error
Link to this function generate_key(filename, opts \\ [])
generate_key(String.t(), [{:prefix, list()}]) :: String.t()

Converts a filename to a unique key.

Examples

iex> Upload.generate_key("phoenix.png")
"b9452178-9a54-5e99-8e64-a059b01b88cf.png"

iex> Upload.generate_key("phoenix.png", prefix: ["logos"])
"logos/b9452178-9a54-5e99-8e64-a059b01b88cf.png"
Link to this function get_extension(filename)
get_extension(String.t() | Upload.t()) :: String.t()

Gets the extension from a filename.

Examples

iex> Upload.get_extension("foo.png")
".png"

iex> Upload.get_extension("foo.PNG")
".png"

iex> Upload.get_extension("foo")
""

iex> {:ok, upload} = Upload.cast_path("/path/to/foo.png")
...> Upload.get_extension(upload)
".png"
Link to this function get_url(key)
get_url(Upload.t() | String.t()) :: String.t()

Get the URL for a given key. It will behave differently based on the adapter you’re using.

Local

iex> Upload.get_url("123456.png")
"/uploads/123456.png"

S3

iex> Upload.get_url("123456.png")
"https://my_bucket_name.s3.amazonaws.com/123456.png"

Fake / Test

iex> Upload.get_url("123456.png")
"123456.png"
Link to this function transfer(upload)
transfer(Upload.t()) :: {:ok, Upload.transferred()} | {:error, String.t()}

Transfer the file to where it will be stored.