Screencast

21. CSV Import with Phoenix LiveView

csv fileupload liveview

Import CSV files in Phoenix LiveView with Preview

def mount(_params, _session, socket) do
  {:ok,
    socket
    |> allow_upload(:brewery_csv, accept: ~w(.csv), max_entries: 1)
    |> assign(:parsed_rows, [])
    |> assign(:sample_breweries, [])}
end

While APIs are a popular choice for data transfer, they're not always available or suitable for every situation. CSV files remain a universally accepted alternative that can be easily exported from spreadsheet software. This tutorial demonstrates how to handle CSV file uploads in Phoenix LiveView with a preview feature, allowing users to validate their data before committing it to the database. We'll build a complete solution that handles file drops, validates content, and provides immediate feedback.

Phoenix LiveView File Upload with CSV Preview

def preview(rows) do
  rows
  |> Enum.take(5)
  |> transform_keys()
  |> Enum.map(&map_to_brewery/1)
end

Building interactive file upload interfaces doesn't have to be complex. Using Phoenix LiveView's built-in upload functionality, we can create a seamless experience where users can drag and drop their CSV files and see a preview of how their data will be processed. This tutorial walks through setting up the upload configuration, handling file processing, and creating a preview mechanism that helps users catch formatting issues before they become problems.

Converting CSV to Database Records in Phoenix

defp transform_keys(rows) do
  rows
  |> Enum.map(fn row ->
    Enum.reduce(row, %{}, fn {key, val}, acc ->
      Map.put(acc, underscore_key(key), val)
    end)
  end)
end

One of the most common challenges when importing CSV data is mapping the CSV headers to your database schema. This tutorial shows you how to build a robust importer that handles the transformation from CSV columns to database fields, complete with proper key transformation and validation. You'll learn how to structure your importer module to keep the code maintainable and testable, while providing clear feedback about successful and failed imports to your users.