Skip to content

File Storage

David Ciulla edited this page Nov 7, 2026 · 2 revisions

File Storage

Laravex's filesystem abstraction is provided by Laravex.Filesystem.Storage. It supports the local driver and S3-compatible object storage — all disk operations are routed through a unified API regardless of which disk you target.


Configuration

Configure disks in config/filesystems.exs:

base_path = Laravex.Foundation.Application.base_path()

%{
  "default" => Laravex.Env.get("FILESYSTEM_DISK", "local"),
  "disks" => %{
    "local" => %{
      "driver" => "local",
      "root"   => Path.join(base_path, "storage/app/private")
    },
    "public" => %{
      "driver"     => "local",
      "root"       => Path.join(base_path, "storage/app/public"),
      "url"        => Laravex.Env.get("APP_URL") <> "/storage",
      "visibility" => "public"
    },
    "s3" => %{
      "driver"                  => "s3",
      "key"                     => Laravex.Env.get("AWS_ACCESS_KEY_ID"),
      "secret"                  => Laravex.Env.get("AWS_SECRET_ACCESS_KEY"),
      "region"                  => Laravex.Env.get("AWS_DEFAULT_REGION", "us-east-1"),
      "bucket"                  => Laravex.Env.get("AWS_BUCKET"),
      "endpoint"                => Laravex.Env.get("AWS_ENDPOINT"),
      "use_path_style_endpoint" => Laravex.Env.get("AWS_USE_PATH_STYLE_ENDPOINT", false)
    }
  },
  "links" => %{
    Path.join(base_path, "public/storage") =>
      Path.join(base_path, "storage/app/public")
  }
}

Disk Drivers

Local driver

Files are read from and written to the local filesystem at the configured root path.

S3 driver

Files are stored in an S3-compatible bucket (AWS S3, MinIO, Cloudflare R2, etc.) via :httpc with optional AWS SigV4 signing — no Hex runtime dependencies required.

Config key Env var Description
key AWS_ACCESS_KEY_ID Access key ID
secret AWS_SECRET_ACCESS_KEY Secret access key
region AWS_DEFAULT_REGION AWS region (default us-east-1)
bucket AWS_BUCKET Bucket name
endpoint AWS_ENDPOINT Custom endpoint URL (for MinIO, R2, etc.)
use_path_style_endpoint AWS_USE_PATH_STYLE_ENDPOINT true for path-style URLs (required by some S3-compatible services)

When key/secret are present, requests are signed with AWS SigV4. Without credentials a stub Authorization header is sent — useful for local emulators that accept unauthenticated requests.

Known S3 limitations: bodies are loaded into memory in full (no streaming); no automatic retry on transient errors; no multi-part upload support.


Obtaining a Disk

# Use the default disk
Laravex.Filesystem.Storage.disk()

# Use a specific disk
Laravex.Filesystem.Storage.disk("public")
Laravex.Filesystem.Storage.disk("s3")

The returned map contains :name, :root, :cfg, and :adapter keys and is used internally. You typically pass the disk name as the last argument to storage functions instead of working with it directly.


Reading and Writing Files

# Write a file (creates parent directories automatically)
Laravex.Filesystem.Storage.put("images/avatar.png", binary_content)
Laravex.Filesystem.Storage.put("images/avatar.png", binary_content, "public")
Laravex.Filesystem.Storage.put("reports/secret.pdf", pdf_data, "local",
  visibility: "private"
)

# Read a file (raises on missing file)
contents = Laravex.Filesystem.Storage.get("images/avatar.png", "public")

# Check existence
Laravex.Filesystem.Storage.exists?("images/avatar.png", "public")  # => true | false
Laravex.Filesystem.Storage.missing?("images/avatar.png", "public") # => true | false

Append and Prepend

# Append to a file (creates if missing)
Laravex.Filesystem.Storage.append("logs/app.log", "new line\n")
Laravex.Filesystem.Storage.append("logs/app.log", "new line\n", "local")

# Prepend to a file (creates if missing)
Laravex.Filesystem.Storage.prepend("logs/app.log", "first line\n")

File Visibility

Laravex supports "public" and "private" visibility. For the local driver, "public" applies 0o644 and "private" applies 0o600 file mode as a best-effort permission.

# Set visibility
Laravex.Filesystem.Storage.set_visibility("exports/data.csv", "private", "local")

# Get visibility
Laravex.Filesystem.Storage.get_visibility("exports/data.csv", "local")
# => "public" | "private" | nil

Visibility can also be set at the disk level in config ("visibility" => "public"), in which case every file written to that disk inherits that visibility unless overridden per-call.


Other File Operations

# Delete a file
Laravex.Filesystem.Storage.delete("old-report.pdf", "local")

# Get a file's size in bytes
Laravex.Filesystem.Storage.size("images/avatar.png", "public")

# Last modification unix timestamp (or nil if missing)
Laravex.Filesystem.Storage.last_modified("images/avatar.png", "public")

# Copy a file within a disk
Laravex.Filesystem.Storage.copy("original.png", "backup.png", "public")

# Move / rename a file within a disk
Laravex.Filesystem.Storage.move("temp/upload.png", "images/avatar.png", "public")

# Guess the MIME type from the file extension
Laravex.Filesystem.Storage.mime_type("images/avatar.png")   # => "image/png"

# Get the absolute filesystem path for a file
Laravex.Filesystem.Storage.path("images/avatar.png", "public")
# => "/var/www/app/storage/app/public/images/avatar.png"

Listing Files and Directories

# Non-recursive: immediate files in a directory
Laravex.Filesystem.Storage.files("images", "public")
# => ["images/avatar.png", "images/banner.jpg"]

# Non-recursive: immediate subdirectories
Laravex.Filesystem.Storage.directories("uploads", "public")
# => ["uploads/2026", "uploads/archive"]

# Recursive: all files under a directory
Laravex.Filesystem.Storage.all_files("uploads", "public")
# => ["uploads/2026/jan.csv", "uploads/2026/feb.csv", …]

# Recursive: all subdirectories
Laravex.Filesystem.Storage.all_directories("uploads", "public")

Storing Uploaded Files

When handling a file upload, pass the %Laravex.Http.UploadedFile{} struct to store/3 or put_file/3. A random 40-character filename is generated automatically.

# store(file, directory, disk) → returns relative path
path = Laravex.Filesystem.Storage.store(uploaded_file, "avatars", "public")
# => "avatars/wq8Xm3kJn7Yv2Pz0dT6Rl4sCeAbUiOh1Q5fNgK9.png"

# Equivalent helper
path = Laravex.Filesystem.Storage.put_file("avatars", uploaded_file, "public")

Store with a Specific Filename

# putFileAs(directory, file, name, disk)
path = Laravex.Filesystem.Storage.put_file_as(
  "avatars",
  uploaded_file,
  "#{user.id}-profile.png",
  "public"
)
# => "avatars/42-profile.png"

File URLs

Generate a URL to a file on the public disk using url/2. The URL is derived from the url key in the disk config, or defaults to /storage/{path}.

url = Laravex.Filesystem.Storage.url("images/avatar.png", "public")
# => "https://example.com/storage/images/avatar.png"
# or "/storage/images/avatar.png" if APP_URL is not set

For S3 disks, the URL is derived from the bucket and region (or the custom endpoint):

url = Laravex.Filesystem.Storage.url("reports/q1.pdf", "s3")
# => "https://my-bucket.s3.us-east-1.amazonaws.com/reports/q1.pdf"

The storage_url/2 Helpers delegates to this function:

import Laravex.Support.Helpers
storage_url("images/avatar.png")            # uses "public" disk
storage_url("reports/data.csv", "local")

Temporary Signed URLs

temporary_url/3 generates a signed URL that expires after a given time. This is most useful for S3 objects, but works with the local disk too.

# Expire in 300 seconds
url = Laravex.Filesystem.Storage.temporary_url("invoices/42.pdf", 300)

# Expire at a specific DateTime
url = Laravex.Filesystem.Storage.temporary_url(
  "exports/users.csv",
  ~U[2026-11-08 00:00:00Z],
  disk: "s3"
)

The signed URL contains an HMAC signature and expiry parameter generated by Laravex.Http.UrlSigner. Requests without a valid signature are rejected with 403 Forbidden.


HTTP Responses

Download

download/2 reads a file from storage and returns a response that triggers a browser download prompt:

def download(request) do
  Laravex.Filesystem.Storage.download("reports/annual.pdf",
    disk: "local",
    as: "Annual Report 2026.pdf"
  )
end
Option Description
:disk Disk name to read from (default: default disk)
:as Download filename shown to the browser (default: basename of the path)

Response (inline)

response/2 serves a file inline (in the browser) rather than as a download:

def show_pdf(request) do
  Laravex.Filesystem.Storage.response("previews/#{request.params["id"]}.pdf",
    disk: "local"
  )
end

Delete a Directory

Laravex.Filesystem.Storage.delete_directory("temp", "public")

Recursively removes the directory and all its contents.


Public Disk and storage:link

The public disk is typically made web-accessible by symlinking public/storage → storage/app/public. Run:

./artisan storage:link

The links to create are configured under filesystems.links in your config. The command reads that map and calls File.ln_s!/2 for each pair, removing any existing link first.

After running storage:link, files in storage/app/public are accessible via /storage/{path}.


Asset URL Helper

The asset/1 Helpers builds a URL for a public asset (not a stored file):

import Laravex.Support.Helpers

asset("js/app.js")
# => "https://example.com/js/app.js" (when APP_URL is set)
# => "/js/app.js" (without APP_URL)

Use storage_url/2 for files managed by Storage, and asset/1 for files in the public/ directory.


See Also

Clone this wiki locally