larshei

larshei

Somehow, I cannot manage to get file uploads to work.

I have read the docs and watched the videos from Chris and also a tutorial at pragmatic studio.

So far, I understand the following:

  1. I need to allow file uploads:
    def mount(params, session, socket) do
      {:ok, socket |> allow_upload(:csv, accept: ~w(.csv), max_entries: 1)}
    end
    
    This will add an @uploads assign that holds a description of the constraints and, once selected, files and upload progress.
  2. And can use the live_file_input to render a file upload button:
    def render(assigns) do
      ~F"""
        <form id="id" for={:data} phx-submit="upload">
          <div class="ui segment" phx-drop-target={@uploads.csv.ref}>
            {live_file_input @uploads.csv}
           </div>
           <p>{inspect @uploads.csv}</p>
           <Button text={gettext "Upload"} icon="upload" extra_attributes="labeled violet"/>
         </form>
      """
    end
    
    Note: Im using Surface UI with Phoenix Live View 0.16.4
    This renders a “Choose File…” button as expected and shows no file selected next to it.
  3. Consume an upload using consume_uploaded_entries. I did not get to this point.

Expectations

With the setup above, I expected

  1. Clicking the “Choose File” button opens a file selector and
  2. when rendering @uploads.csv after selecting a file it contains information on the selected file in its :entry field.

What happens

  1. Clicking the “Choose File” button does not do anything in Chrome. In Safari, a file browser is opened.
  2. After selecting a file in Safari, the @uploads assign seems to not contain anything (<p>{inspect @uploads.csv}</p>):
    #Phoenix.LiveView.UploadConfig<
     accept: ".csv", auto_upload?: false, entries: [], errors: [], max_entries: 1, max_file_size: 8000000, name: :csv, progress_event: nil, ref: "phx-FtoOkG01s4jRVQ-F", ...
    >
    

I am not sure if something is missing and would appreciate ideas/hints on what to check :slight_smile:

Solutions

Solution to missing info in @upload assigns:
As @Xty mentioned below, a phx-change is required on the form (which can simply return {:noreply, socket}) to properly update the @uploads assign.

Showing Posts 1 to 5

Xty

Xty

It’s hard to tell if the code samples you’ve provided are complete or boiled down examples, but I’m fairly sure that the LiveView upload features are expected to be used from within a form element.

Have you tried putting the live_file_input inside of a form? If not, I think that would be a good place to start.

Another thing that has caused me issues with live uploads is not having a phx-change handler on the form. Even if that handler does nothing but respond {:noreply, socket} it’s still needed for live uploads.

I’d recommend reading through the official documentation if you haven’t, it should cover everything you need and is likely more up-to-date than the videos you’ve mentioned.

larshei

larshei OP

You are right, it was inside a form.
I minimized the example a bit too much and have added the form to the initial post.

phx-change was missing as you mentioned. Adding it to the form now updates the socket data correctly, so it fixed one of my two issues :slight_smile:

Now that you mention it, I recognized this is actually mentioned in the docs :see_no_evil:

Important: You must bind phx-submit and phx-change on the form.

However, Chrome still does not work at all, as no file browser is opened on button click.

larshei

larshei OP

For Chrome, drag&drop with the phx-drop-target works, just the button does not.

03juan

03juan

I just tested this with my Chrome file inputs, because I’ve had no problems clicking it, and realised that I’m using a label element in place of your div.

When I change my element to div, drop works but click stops working. Even the section element in the Upload Entries doc example doesn’t work with Chrome. This is either a browser bug or something in the live_view.js, not really sure.

kartheek

kartheek

I use this code and it works in safari and chrome (I use bootstrap for css). I had an error which says some id does not match on upload - but that was because I was creating two livesockets in a single page due two different js files(which I included by mistake).

Also I had to add phx-change="validate" for validate to trigger.

<form id="upload-form" phx-submit="save" phx-change="validate">
      <div class="border d-flex align-items-center justify-content-center mb-3" phx-drop-target={@uploads.cassette.ref}>
          <%= live_file_input @uploads.cassette, class: "visually-hidden", tabindex: "0" %>
          <.icon class="bi-upload" size="3"></.icon>
          <.div px_3>Drag And Drop Cassettes</.div>
      </div>
      <section>
        <%# render each avatar entry %>
        <%= for entry <- @uploads.cassette.entries do %>
          <article class="upload-entry">

            <figure>
              <%# Phoenix.LiveView.Helpers.live_img_preview/2 renders a client-side preview %>
              <%# live_img_preview entry %>
              <figcaption><%= entry.client_name %></figcaption>
            </figure>

            <%# entry.progress will update automatically for in-flight entries %>
            <progress value={entry.progress} max="100"> <%= entry.progress %>% </progress>

            <%# a regular click event whose handler will invoke Phoenix.LiveView.cancel_upload/3 %>
            <button phx-click="cancel-upload" phx-value-ref={entry.ref} aria-label="cancel">&times;</button>

            <%# Phoenix.LiveView.Helpers.upload_errors/2 returns a list of error atoms %>
            <%= for err <- upload_errors(@uploads.cassette, entry) do %>
              <.alert danger><%= error_to_string(err) %></.alert>
            <% end %>

          </article>
        <% end %>

        <%# Phoenix.LiveView.Helpers.upload_errors/1 returns a list of error atoms %>
        <%= for err <- upload_errors(@uploads.cassette) do %>
          <.alert danger><%= error_to_string(err) %></.alert>
        <% end %>
      </section>
      <%= if @uploads.cassette.entries != [] do %>
      <.button submit primary>Upload</.button>
      <% end %>
    </form>

I derived this code from the live_view docs.


OP included solution in his post.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews