arpan

arpan

Live view Uploads get deleted before processing on heroku

Hi everyone, I have created a project which involves live view file uploads but I am facing a weird problem.

After the user uploads a file, I copy the uploaded file to a directory and then upload it to S3 using Arc.

This works fine in my local development environment however after deploying to Heroku the uploaded file is not found for some reason leading to an error when I try to copy the file.

2021-01-26T13:00:47.055190+00:00 app[web.1]: ** (File.CopyError) could not copy from "/tmp/plug-1611/live_view_upload-1611666046-602244053833136-3" to "priv/static/uploads/live_view_upload-1611666046-602244053833136-3": no such file or directory
2021-01-26T13:00:47.055191+00:00 app[web.1]: (elixir 1.11.2) lib/file.ex:816: File.cp!/3

The destination directory priv/static/uploads/ does exists on heroku so the problem is with the source that is /tmp/plug-1611/live_view_upload-1611666046-602244053833136-3 I believe.

Here’s the relevant code…

From my live view

@impl Phoenix.LiveView
  def handle_event("update_profile", %{"profile" => params}, socket) do
    params =
      if socket.assigns.remove_existing_avatar, do: Map.put(params, "avatar", nil), else: params

    Logger.warn(File.ls!("/tmp"))  # This shows that /tmp/plug-1611 does exist at this point
    socket.assigns.user
    |> Accounts.update_profile(params)
    |> case do
      {:error, profile_changeset} ->
        {
          :noreply,
          socket
          |> assign(profile_changeset: profile_changeset |> Map.put(:action, :insert))
          |> clear_flash()
          |> put_flash(:error, "Failed to update profile, check for errors")
        }

      _ ->
        case handle_avatar_upload(socket, socket.assigns.user) do
          {:error, _} ->
            {
              :noreply,
              socket
              |> put_flash(:error, "Avatar upload failed")
            }

          _ ->
            {
              :noreply,
              socket
              |> put_flash(:info, "Profile updated successfully")
              |> redirect(to: Routes.settings_path(socket, :index))
            }
        end
    end
  end

  def handle_avatar_upload(socket, user) do
    consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
      dest = Path.join("priv/static/uploads", Path.basename(path))
      File.cp!(path, dest)  # ERROR HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      dest
    end)
    |> case do
      [file_path] ->
        case Avatar.store({file_path, user}) do
          {:ok, img_url} ->
            File.rm(file_path)
            Accounts.update_avatar(user, img_url)

          _ ->
            File.rm(file_path)
            {:error, "Image upload failed"}
        end

      _ ->
        :ok
    end
  end

I don’t understand why this problem would occur in Heroku and not in my local development environment.

I am stuck with this, any help or advice will be very helpful for me.

Marked As Solved

arpan

arpan

I found a fix finally after long hours of debugging.

Turns out the problem was not in the source but the destination path passed to File.cp!

Changing this…

consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
      dest = Path.join("priv/static/uploads", Path.basename(path))
      File.cp!(path, dest)  # ERROR HERE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
      dest
    end)

to…

    consume_uploaded_entries(socket, :avatar, fn %{path: path}, _entry ->
      File.mkdir("uploads")
      dest = Path.join("uploads", Path.basename(path))
      File.cp!(path, dest)
      dest
    end)

Fixed the issue, I suspect this is because of some relative path issue with Path.join("priv/static/uploads", Path.basename(path))

This happened in Heroku and not on my local environment probably because the current directory was set correctly in my local environemnt so “priv/static/uploads” was found.

Also Liked

al2o3cr

al2o3cr

FWIW, if you need to reliably reference “application :some_app’s priv directory” it’s best to use :code.priv_dir(:some_app) and avoid working-directory hassles.

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
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
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New

Other popular topics Top

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
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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 30877 112
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement