Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท LiveView

LiveView Uploads

Handle file uploads in LiveView with allow_upload, live_file_input, progress, previews, validation errors and consume_uploaded_entries, including external storage.

File uploads are usually painful: multipart forms, progress bars, previews and validation all need custom JavaScript. LiveView ships with an upload system that handles the browser side for you. You declare what you accept in mount/3, render a special input, and the server receives the file in chunks over the same WebSocket. Progress, previews and error messages come for free as assigns.

The real framework cannot run on this site, so Phoenix code is read-only here. The editors model the ideas in JavaScript: validating files by size and type, and processing them in chunks.

Step 1: allow the upload

Call allow_upload/3 on the socket. The options describe the rules; the server enforces them, not just the browser.

ELIXIR
def mount(_params, _session, socket) do
  {:ok,
   socket
   |> assign(:uploaded_files, [])
   |> allow_upload(:avatar,
     accept: ~w(.jpg .jpeg .png .webp),
     max_entries: 1,
     max_file_size: 2_000_000
   )}
end

The name :avatar identifies the upload and becomes @uploads.avatar in the template. The most useful options are:

Option Meaning
:accept List of extensions or MIME types; :any allows everything
:max_entries How many files at once (default 1)
:max_file_size Bytes per file (default 8 MB)
:auto_upload Start uploading as soon as a file is chosen
:chunk_size Bytes sent per message (default 64 KB)
:external Upload straight to cloud storage (see below)

Step 2: render the input

live_file_input/1 renders the <input type="file"> and wires it to the upload. It must sit inside a form that has a phx-change event, even if the handler does nothing, because that is how LiveView validates files as they are chosen.

HEEX
<form id="upload-form" phx-submit="save" phx-change="validate">
  <.live_file_input upload={@uploads.avatar} />

  <section phx-drop-target={@uploads.avatar.ref}>
    <article :for={entry <- @uploads.avatar.entries}>
      <.live_img_preview entry={entry} width="80" />
      <progress value={entry.progress} max="100"><%= entry.progress %>%</progress>
      <button type="button" phx-click="cancel" phx-value-ref={entry.ref}>cancel</button>

      <p :for={err <- upload_errors(@uploads.avatar, entry)} class="error">
        <%= error_to_string(err) %>
      </p>
    </article>
  </section>

  <button type="submit">Save</button>
</form>

What you get for free:

  • @uploads.avatar.entries lists the chosen files, each with progress (0 to 100), client_name, client_size and ref.
  • <.live_img_preview> shows a local preview before anything is sent.
  • phx-drop-target turns an element into a drag-and-drop zone.
  • upload_errors/2 returns errors per entry, and upload_errors/1 returns errors for the whole input, such as :too_many_files.

Error atoms are :too_large, :not_accepted, :too_many_files and a few more; you turn them into friendly text with a small helper:

ELIXIR
defp error_to_string(:too_large), do: "That file is over 2 MB."
defp error_to_string(:not_accepted), do: "Use a JPG, PNG or WebP image."
defp error_to_string(:too_many_files), do: "Only one file, please."

Step 3: consume on submit

Uploaded bytes sit in a temporary file until you decide what to do. consume_uploaded_entries/3 runs your function for each finished entry; the file at path is deleted afterwards, so you must copy or move it inside the function.

ELIXIR
def handle_event("validate", _params, socket), do: {:noreply, socket}

def handle_event("cancel", %{"ref" => ref}, socket) do
  {:noreply, cancel_upload(socket, :avatar, ref)}
end

def handle_event("save", _params, socket) do
  urls =
    consume_uploaded_entries(socket, :avatar, fn %{path: path}, entry ->
      ext = Path.extname(entry.client_name)
      dest = Path.join(upload_dir(), "#{Ecto.UUID.generate()}#{ext}")
      File.cp!(path, dest)
      {:ok, ~p"/uploads/#{Path.basename(dest)}"}
    end)

  {:noreply, update(socket, :uploaded_files, &(&1 ++ urls))}
end

The function returns {:ok, value} (the values are collected into the list) or {:postpone, value} to keep the file for later. Never trust entry.client_name for the stored name: it is user input. Generate your own file name, as above, to avoid collisions and path tricks (see web security).

:accept checks the file extension and the type the browser reports. It does not inspect the content. If a wrong file type would be dangerous (for example, anything you later serve as HTML), also check the first bytes ("magic numbers") yourself inside consume_uploaded_entries/3.

Large files and cloud storage

For big files, sending every byte through your server is wasteful. With external: &presign_upload/2 the browser uploads directly to S3 or a similar service. Your function returns the target URL and form fields (a presigned POST), and LiveView hands that to its JavaScript uploader:

ELIXIR
allow_upload(socket, :video, accept: ~w(.mp4), max_file_size: 500_000_000, external: &presign_upload/2)

defp presign_upload(entry, socket) do
  key = "videos/#{Ecto.UUID.generate()}-#{entry.client_name}"
  {:ok, %{uploader: "S3", key: key, url: bucket_url(), fields: sign(key)}, socket}
end

The uploader: "S3" value names a JavaScript function you register in app.js. After the upload, consume_uploaded_entries/3 gets only metadata, because the bytes are already in the bucket.

A runnable model

This stand-in applies the same rules as allow_upload: accepted extensions, a size limit and a maximum entry count, with the same error atoms.

Node.js Validate entries like allow_upload (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second model shows chunked transfer and progress. LiveView sends 64 KB chunks by default; here a tiny chunk size keeps the output short.

Node.js Chunked upload with progress (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing uploads

LiveViewTest has file_input/4 and render_upload/3, so you can test validation and saving without a browser (more in testing LiveView):

ELIXIR
avatar = file_input(lv, "#upload-form", :avatar, [%{name: "me.png", content: png_bytes, type: "image/png"}])
assert render_upload(avatar, "me.png") =~ "100%"

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function declares the rules for an upload in mount/3?

    allow_upload/3 sets accepted types, size limits and entry counts. The other functions render, consume or cancel.
  2. 2. What happens to the temporary upload file after consume_uploaded_entries/3 runs your function?

    The temp path only exists during your callback. Copy it to permanent storage there.
  3. 3. Why must live_file_input sit inside a form with phx-change?

    The change event carries the file metadata to the server, which checks it against allow_upload rules.
  4. 4. What is the best way to name the stored file?

    client_name is user input. Your own name avoids collisions and path tricks.

Summary

  • allow_upload/3 declares accepted types, size and entry limits; the server enforces them.
  • live_file_input/1, live_img_preview/1, phx-drop-target and upload_errors/2 provide the UI.
  • consume_uploaded_entries/3 is where you copy the temp file somewhere permanent.
  • Use external: uploads to send large files straight to cloud storage.
  • Extension checks are not content checks; validate bytes when it matters.

Next: Channels and Sockets