10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ElixirAdvent Calendar 2023

Day 16

Phoenixframework 画像Uploads & 画像表示 & 画像ダウンロード

Posted at

Phoenix 1.7 になって、色々と書き方が変わり、調べるのに時間かかったので、備忘録

    <%= for {_ref, err} <- @uploads.avatar.errors do %>
      <p class="alert"><%= Phoenix.Naming.humanize(err) %></p>
    <% end %>

    <%= for entry <- @uploads.avatar.entries do %>
      <%= entry.client_name %> - <%= entry.progress %>%
      <.live_img_preview entry={entry} width={75} />
    <% end %>

    <form phx-submit="avatar_save" phx-change="validate">
      <.live_file_input upload={@uploads.avatar} />
      <button type="submit">Upload</button>
    </form>
def mount(_params, _session, socket) do

    socket =
      socket
      |> assign(:uploaded_files, [])
      |> allow_upload(:avatar, accept: ~w(.png .jpeg .jpg), max_entries: 1)

    {:ok, socket}
  end
  @impl true
  def handle_event("avatar_save", params, socket) do

    uploaded_files =
      consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
        dest = Path.join([:code.priv_dir(:pansy), "static", "uploads", Path.basename(path)])
        File.cp!(path, dest)
        {:ok, ~p"/uploads/#{Path.basename(dest)}"}
      end)

    {:noreply, update(socket, :uploaded_files, &(&1 ++ uploaded_files))}
  end
  def handle_event("validate", _, socket) do
    # ここで任意の検証を行うことができます
    {:noreply, socket}
  end

別の書き方

    uploaded_files =
      consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
        dest = Path.join("priv/static/uploads", Path.basename(path))
        File.cp!(path, dest)
        {:ok, ~p"/uploads/#{Path.basename(dest)}"}
        Phoenix.VerifiedRoutes.static_path(socket.endpoint, "/uploads/#{Path.basename(dest)}")
10
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?