Nex.Upload (nex_core v0.4.3)

Copy Markdown

File upload handling for Nex applications.

Usage

Files are automatically parsed from multipart form data and available in req.body.

def post(req) do
  # req.body["avatar"] is a %Plug.Upload{} struct
  case req.body["avatar"] do
    nil ->
      Nex.json(%{error: "No file uploaded"}, status: 400)

    upload ->
      # Save to disk
      case save(upload, "priv/uploads") do
        {:ok, path} ->
          Nex.json(%{url: path})

        {:error, reason} ->
          Nex.json(%{error: reason}, status: 500)
      end
  end
end

File Validation

def post(req) do
  upload = req.body["file"]

  # Validate before saving
  case validate(upload, max_size: 5_000_000, types: ["image/jpeg", "image/png"]) do
    :ok ->
      save(upload, "priv/uploads")

    {:error, reason} ->
      Nex.json(%{error: reason}, status: 400)
  end
end

Summary

Functions

Saves an uploaded file to disk.

Saves with a custom filename (avoids filename conflicts).

Validates an upload before saving.

Types

result()

@type result() :: {:ok, String.t()} | {:error, String.t()}

upload()

@type upload() :: %Plug.Upload{content_type: term(), filename: term(), path: term()}

Functions

save(upload, dir)

Saves an uploaded file to disk.

Arguments

  • upload - %Plug.Upload{} struct from req.body
  • dir - Directory to save to (created if not exists)

Returns

  • {:ok, "/uploads/filename.jpg"} - Relative URL path
  • {:error, "reason"} - Error message

save(original_upload, dir, opts \\ [])

@spec save(upload(), String.t(), keyword()) :: result()

Saves with a custom filename (avoids filename conflicts).

Arguments

  • upload - %Plug.Upload{} struct
  • dir - Directory to save to
  • options - [prefix: "custom_"] to add prefix

validate(upload, opts)

@spec validate(
  upload() | nil,
  keyword()
) :: :ok | {:error, String.t()}

Validates an upload before saving.

Options

  • :max_size - Maximum file size in bytes (e.g., 5_000_000 for 5MB)
  • :types - Allowed MIME types (e.g., ["image/jpeg", "image/png"])
  • :exts - Allowed extensions (e.g., [".jpg", ".png"])

Returns

  • :ok - Validation passed
  • {:error, "reason"} - Validation failed