Storage (PhoenixContribStorage v0.1.0)

View Source

ActiveStorage-like file storage for Phoenix.

Storage provides a unified interface for handling file uploads in Phoenix applications, supporting multiple storage backends and following the design principles of Rails ActiveStorage.

Features

  • Multiple storage backends (local filesystem, S3, etc.)
  • Direct uploads with signed URLs
  • Image processing and variants
  • Ecto schema integration
  • Phoenix LiveView support
  • Configurable storage services

Configuration

Add to your config.exs:

config :storage,
  default_service: :local,
  services: %{
    local: {Storage.Services.Local, root: "/tmp/storage"},
    s3: {Storage.Services.S3, bucket: "my-bucket", region: "us-east-1"}
  }

Usage

In your schema

defmodule MyApp.User do
  use Ecto.Schema
  use Storage.Attachment

  schema "users" do
    field :name, :string
    has_one_attached :avatar
    has_many_attached :documents
  end
end

In your LiveView

def handle_event("save", %{"user" => user_params}, socket) do
  uploaded_files =
    consume_uploaded_entries(socket, :avatar, fn %{path: path}, entry ->
      {:ok, Storage.put_file(path, filename: entry.client_name)}
    end)

  # Use uploaded_files...
end

Summary

Functions

Deletes a file from storage.

Retrieves a file from storage.

Purges orphaned blobs that are not attached to any records.

Stores a file and returns a Blob struct.

Generates a signed URL for direct uploads.

Functions

delete_file(blob)

Deletes a file from storage.

Examples

Storage.delete_file(blob)
Storage.delete_file(blob.key)

get_file(blob)

Retrieves a file from storage.

Examples

Storage.get_file(blob)
Storage.get_file(blob.key)

purge_unattached(older_than \\ %{days: 7})

Purges orphaned blobs that are not attached to any records.

put_file(file, opts \\ [])

Stores a file and returns a Blob struct.

Examples

Storage.put_file("/path/to/file.jpg", filename: "avatar.jpg")
Storage.put_file(file_binary, filename: "document.pdf", content_type: "application/pdf")

signed_url_for_direct_upload(opts \\ [])

Generates a signed URL for direct uploads.

Examples

Storage.signed_url_for_direct_upload(filename: "image.jpg", content_type: "image/jpeg")