I’m using Live Upload with max_entries set to 5 and I’d like to store each image name inside the database. I can do this just fine with one image:
defp put_photo_urls(socket, photo) do
uploaded_photo =
consume_uploaded_entries(socket, :photo, fn %{path: path}, entry ->
photo_name = "#{entry.uuid}.#{ext(entry)}"
# entry.client_name will give you original name of file
dest =
Path.join(Application.app_dir(:live_welp, "priv/static/uploads"), photo_name)
# You will need to create `priv/static/uploads` for `File.cp!/2` to work.
# File.cp!(path, dest)
{:ok, photo_name}
end)
%{
photo
| "photo_url" => List.first(uploaded_photo)
}
end
def handle_event("save", %{"photo" => params}, socket) do
params = put_photo_urls(socket, params)
save_photo(socket, params)
end
defp save_photo(socket, params) do
IO.inspect(params)
case Listing.create_photo(params) do
{:ok, _photo} ->
{:noreply,
socket
|> put_flash(:info, "Photo saved")
|> redirect(to: ~p"/biz")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, form: to_form(changeset, as: "photo"))}
end
end
But if I allow for multiple image uploads I only get one photo_url. I’ve tried to store all the image URLs in a List in put_photo_urls method and then Enum.map over that List, something like this:
def handle_event("save", %{"photo" => params}, socket) do
photo_list = put_photo_urls(socket, params)
Enum.map(photo_list, fn url -> %{params | "photo_url" => url } end)
end
But that isn’t working, any idea how I can do this?