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
endFile 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
Functions
Saves an uploaded file to disk.
Arguments
upload- %Plug.Upload{} struct from req.bodydir- Directory to save to (created if not exists)
Returns
{:ok, "/uploads/filename.jpg"}- Relative URL path{:error, "reason"}- Error message
Saves with a custom filename (avoids filename conflicts).
Arguments
upload- %Plug.Upload{} structdir- Directory to save tooptions- [prefix: "custom_"] to add prefix
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