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)}")