ppetrov

ppetrov

Need help with live image upload - doesn't save to DB

Hello, newbie here.

I am trying to implement live file upload. So far i got to the point i can upload the file and get the params correctly. However it does not save the params to the DB so i can’t really display the data. For some reason after uploading the files just before the save part it reloads and does not go to saving the data to DB.

This is my render function:

def render(assigns) do
    ~H"""

      <div class="p-10 md:p-[100px]">



            <.simple_form for={@changeset} id="nomenee-form" phx-change="validate" phx-submit="save" >
            <div class="font-bold text-center mb-20 w-full font-comfortaa text-purple-900 text-2xl"> Номинация в област "Любим университетски преподавател в област Логопедия"</div>

                <%= inspect(@uploads.image) %>
              <.input field={@form[:name]} type="text" label="Име"  />

                <.input field={@form[:description]} type="textarea" label="Описание" />
                <div class="container" phx-drop-target={@uploads.image.ref}>
                <.live_file_input upload={@uploads.image} />
                </div>

                <div :for={entry <- @uploads.image.entries} class="entry">
                <.live_img_preview entry={entry} />

                <div class="progress">
                  <.error :for={err <- upload_errors(@uploads.image, entry)}>
                    <%= Phoenix.Naming.humanize(err) %>
                  </.error>
                  </div>
                  </div>
                <.live_select field={@form[:category_id]} placeholder="Категория"  />
                <.input field={@form[:published]} type="checkbox" label="Публикуван" phx-update="ignore" />



                <:actions>

                <.button phx-disable-with="Изпращане...">Изпрати номинацията</.button>

                </:actions>

            </.simple_form>

      </div>


                <%= # inspect @townoptions, pretty: true %>

    """

  end

This is my schema:

defmodule Logonag.Nomenees.Nomenee do
  use Ecto.Schema
  import Ecto.Changeset

  schema "nomenees" do
    field :name, :string
    field :description, :string
    field :image, :string
    field :published, :boolean
    field :category_id, :id

    timestamps()
  end

  @doc false
  def changeset(nomenee, attrs) do
    nomenee
    |> cast(attrs, [:name, :description, :published, :category_id, :image])
    |> validate_required([:name, :description, :published, :category_id, :image])
  end
end

This is my save function:


def handle_event("save", %{"nomenee" => nomenee_params}, socket) do
  
  photo_locations =
    consume_uploaded_entries(socket, :image, fn meta, entry ->
      dest =
        Path.join([
          "priv",
          "static",
          "uploads",
          "#{entry.uuid}-#{entry.client_name}"
        ])

      File.cp!(meta.path, dest)

      url_path = static_path(socket, "/uploads/#{Path.basename(dest)}")

      {:ok, url_path}
    end)

    nomenee_params = Map.put(nomenee_params, "image", photo_locations)

    IO.inspect(nomenee_params, label: "nomenee_params------------")
  case Nomenees.create_nomenee(nomenee_params) do
    {:ok, _nomenee} ->
      changeset = Nomenees.change_nomenee(%Nomenee{})
      {:noreply, assign(socket, :form, to_form(changeset))}
    {:error, %Ecto.Changeset{} = changeset} ->
      {:noreply, assign(socket, :form, to_form(changeset))}
      end
end

From my log i have the inspect of the nomenee_params and then it re-mounts and never pushes the changes to db:

nomenee_params------------: %{
  "category_id" => "2",
  "category_id_text_input" => "cat 2",
  "description" => "sadf",
  "image" => ["/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg"],
  "name" => "asdf",
  "published" => "true"
}
[debug] Replied in 5ms
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[debug] Live reload: priv/static/uploads/b3d164ae-cae7-4c89-9c49-e02424037e6d-gergana-markova.jpg
[info] GET /nomenees
Mounted started

I have tried to put the last bit in private function but got the same result. Please help me understand what i am missing here.

Regards,
Peter

Marked As Solved

thomas.fortes

thomas.fortes

photo_locations is a list, in your schema you want a string, since you’re uploading a single image you can just get the head of the list when passing to params.

nomenee_params = Map.put(nomenee_params, "image", hd(photo_locations))

Also Liked

sodapopcan

sodapopcan

On the off chance you will be uploading to priv/static in production, use :code.priv_dir(:my_app) (:my_app being the name of your app) as the priv/ is in a different location in production.

This could be viewed as nit-picky but I always pattern match (note singular photo_location):

[photo_location] =
  consume_uploaded_entries(socket, :image, fn meta, entry ->
    # ...
  end

nomenee_params = Map.put(nomenee_params, "image", photo_location)

This way if something exceptional happens like someone somehow manages to upload more than one image (meaning they are probably up to no good), it will crash. It also reads more explicitly in that you are asserting there should only one entry.

Last Post!

sodapopcan

sodapopcan

On the off chance you will be uploading to priv/static in production, use :code.priv_dir(:my_app) (:my_app being the name of your app) as the priv/ is in a different location in production.

This could be viewed as nit-picky but I always pattern match (note singular photo_location):

[photo_location] =
  consume_uploaded_entries(socket, :image, fn meta, entry ->
    # ...
  end

nomenee_params = Map.put(nomenee_params, "image", photo_location)

This way if something exceptional happens like someone somehow manages to upload more than one image (meaning they are probably up to no good), it will crash. It also reads more explicitly in that you are asserting there should only one entry.

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36654 110
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31494 112
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement