I’m trying to implement a custom made button (what I mean by custom made, not using the regular choose file button) that when I click on it I shall choose my desired file and automatically it parses the file, validates it and inserts in the table. But as for now i have a problem with parsing the data
-
what i tried:
i tried using the uploads method and it works like a gem but i must use the regular design which is the choose file not a custom made button here is the codedef mount(_params, _session, socket) do {:ok, socket |> assign(:parsed_rows, []) |> assign(:imported_customers, []) |> assign(:sample_customers, []) |> assign(:uploaded_files, []) |> allow_upload(:sample_csv, accept: ~w(.csv .xlsx), max_entries: 1)} end def handle_event("validate", _params, socket) do {:noreply, socket} end def handle_event("parse", _, socket) do parsed_rows = parse_csv(socket) IO.inspect(parsed_rows) { :noreply, socket |> assign(:parsed_rows, parsed_rows) |> assign(:uploaded_files, []) } end defp parse_csv(socket) do consume_uploaded_entries(socket, :sample_csv, fn %{path: path}, _entry -> rows = path |> File.stream!() |> CSV.decode!(headers: true) |> Enum.to_list() {:ok, rows} end) |> List.flatten() end def render(assigns) do ~H""" <div class="my-12"> <.form id="upload-form" phx-submit="parse" phx-change="validate" class="space-y- 2"> <div class="p-4 border border-zinc-200 rounded"> <.live_file_input upload={@uploads.sample_csv} /> </div> <.button type="submit">Upload</.button> </.form></div> """ end
-
I tried also removing the live input and gave it a label but the parsing data returns an
empty list every time. I gave the phx-submit and the phx-change the same name as i want the button to automatically uploads it after i choose the file. help if I’m wrong<.form phx-change="parse" phx-submit="parse"> <label for="file-upload" class="flex items-center cursor-pointer"> <span class="bg-[#F7F7F7] p-2 rounded-xl">Upload Excel</span> </label> <input type="file" id="file-upload" name="sample_csv" hidden /> </.form>
-
also i tried giving the live_input class hidden and implement my own button but that also didn’t work
shall i use a different approach other than the uploads? or there is a way in creating a custom made button for uploading? Please help