PhxMediaLibrary.Storage behaviour (PhxMediaLibrary v0.6.1)

Copy Markdown View Source

Behaviour for storage adapters.

PhxMediaLibrary ships with the following adapters:

Implementing a Custom Adapter

defmodule MyApp.Storage.CustomAdapter do
  @behaviour PhxMediaLibrary.Storage

  @impl true
  def put(path, content, opts) do
    # Store content at path
    :ok
  end

  # ... implement other callbacks
end

Then configure it:

config :phx_media_library,
  disks: [
    custom: [
      adapter: MyApp.Storage.CustomAdapter,
      # adapter-specific options
    ]
  ]

Summary

Callbacks

Delete the file at the given path.

Check if a file exists at the given path.

Retrieve content from the given path.

Get the full filesystem path (local storage only).

Generate a presigned URL for direct client-to-storage uploads.

Store content at the given path.

Get a URL for the file.

Types

content()

@type content() :: binary() | {:stream, Enumerable.t()}

opts()

@type opts() :: keyword()

path()

@type path() :: String.t()

presigned_opts()

@type presigned_opts() :: [
  expires_in: pos_integer(),
  content_type: String.t(),
  content_length_range: {non_neg_integer(), pos_integer()}
]

url_opts()

@type url_opts() :: [
  signed: boolean(),
  expires_in: pos_integer(),
  content_type: String.t(),
  disposition: String.t()
]

Callbacks

delete(path, opts)

@callback delete(path(), opts()) :: :ok | {:error, term()}

Delete the file at the given path.

exists?(path, opts)

@callback exists?(path(), opts()) :: boolean()

Check if a file exists at the given path.

get(path, opts)

@callback get(path(), opts()) :: {:ok, binary()} | {:error, term()}

Retrieve content from the given path.

path(path, opts)

(optional)
@callback path(path(), opts()) :: String.t() | nil

Get the full filesystem path (local storage only).

presigned_upload_url(path, presigned_opts, opts)

(optional)
@callback presigned_upload_url(path(), presigned_opts(), opts()) ::
  {:ok, String.t(), map()} | {:error, term()}

Generate a presigned URL for direct client-to-storage uploads.

Returns {:ok, url, fields} where url is the upload endpoint and fields is a map of form fields (for POST-based uploads) or an empty map (for PUT-based uploads).

Only applicable to remote storage backends (e.g. S3). Local storage adapters do not need to implement this callback.

Options

  • :expires_in — URL expiration in seconds (default: adapter-specific)
  • :content_type — expected content type of the upload
  • :content_length_range{min, max} byte range tuple for upload size validation

put(path, content, opts)

@callback put(path(), content(), opts()) :: :ok | {:error, term()}

Store content at the given path.

url(path, opts)

@callback url(path(), opts()) :: String.t()

Get a URL for the file.