defmodule LivebookWeb.SessionLive.CellUploadComponent do use LivebookWeb, :live_component alias Livebook.Session @impl true def mount(socket) do {:ok, assign(socket, name: "")} end @impl true def render(assigns) do ~L"""

Insert image

<%= if @uploads.cell_image.errors != [] do %>
Invalid image file. The image must be either GIF, JPEG, or PNG and cannot exceed 5MB in size.
<% end %> <%= for entry <- @uploads.cell_image.entries do %>
<%= entry.client_name %> <%= entry.progress %>%
<% end %>
<%= live_patch "Cancel", to: @return_to, class: "button button-outlined-gray" %> <%= content_tag :button, "Upload", type: :submit, class: "button button-blue", disabled: @uploads.cell_image.entries == [] or @name == "" %>
""" end @impl true def handle_event("validate", %{"name" => name}, socket) do {:noreply, assign(socket, name: name)} end def handle_event("save", %{"name" => name}, socket) do %{images_dir: images_dir} = Session.get_summary(socket.assigns.session_id) File.mkdir_p!(images_dir) [filename] = consume_uploaded_entries(socket, :cell_image, fn %{path: path}, entry -> ext = Path.extname(entry.client_name) filename = name <> ext dest = Path.join(images_dir, filename) File.cp!(path, dest) filename end) src_path = "images/#{filename}" {:noreply, socket |> push_patch(to: socket.assigns.return_to) |> push_event("cell_upload", %{cell_id: socket.assigns.cell.id, url: src_path})} end end