GeorgeMiller

GeorgeMiller

With Liveview, what is best way to download a file to the user's browser?

I am coding my first Liveview application. Liveview is awesome, but I have been stumped on something for several days now and need some help.

My Liveview application needs to download a file to the client’s browser. My Liveview page renders a button for doing the download.

Summary of behaviour that I see:
a) The controls (dropboxes, buttons) on the Liveview page work fine
b) When the Download button is pressed, the file is downloaded. The displayed page is still the Liveview page.
c) At this point, the Liveview code stops working. The controls no longer work (including the Download button).

Liveview supports uploads out-of-the-box, but does not support downloads. I found two threads (one and two) which say that in order to download a file, it is recommended to redirect to a
Phoenix Controller.

My Liveview application redirects to a Phoenix controller, which in turn downloads the file. This part works fine. There are several options for downloading files to the client browser (Phoenix.Controller.send_download, Plug.Conn.send_file, or Plug.Conn.chunk). All of these options make use of the ‘Conn’ object.

My Liveview code that handles the download button event:

@impl true
def handle_event("download-btn-event", _, socket) do
    {:noreply, socket |> redirect(to: "/api/download")}
end

And an exerpt of router.ex:

scope "/api", MyApplicationWeb.Api, as: :api do
    pipe_through :api
    get "/download", DownloadController, :download
end

And the Phoenix Controller code is defined like this:

defmodule MyApplicationWeb.Api.DownloadController do
    use MyApplicationWeb, :controller

    @filename "Downloaded.csv"

    def download(conn, params) do
        conn =
            conn
            |> put_resp_content_type("text/csv")
            |> put_resp_header("content-disposition", ~s[attachment; filename="#{@filename}"])
            |> ...
            |> Phoenix.Controller.send_download({:file, path})
    #     |> Phoenix.Controller.redirect(to: "/myapplication")
    #     |> halt

Inside this Phoenix controller action I have tried returning Conn, or redirecting the connection back to liveview (to use my router.ex to bring the user back to Liveview page), or halting the Conn process. The commented out stuff are ideas I was trying. In particular, the redirect idea gives an error like this:

** (exit) an exception was raised:
** (Plug.Conn.AlreadySentError) the response was already sent

I found this excerpt at Plug.Conn — Plug v1.20.2 :

The connection state is used to track the connection lifecycle. It starts as :unset but is changed to :set (via resp/3) or :set_chunked (used only for before_send callbacks by send_chunked/2) or :file (when invoked via send_file/3). Its final result is :sent, :file or :chunked depending on the response model.

I think the above shown error is because the Conn was already used to send the file, and so it does not allow the Conn to be re-used for another purpose (like redirecting to another page) ?

Once the file has been downloaded, I want the user to continue interacting with the Liveview.

An alternate idea I has was to spawn a separate process for doing the download (for example: following advice like Setup a supervised background task in Phoenix or this thread on handling background jobs with elixir/phoenix. And sure enough I am able to spawn a background process, but that process does not have a ‘Conn’ object so it can’t do the file download.

So, I’m stuck.

Questions:

  1. How to redirect from Liveview to Phoenix, get the file downloaded to the user, and then redirect back to Liveview again (need to re-use the Conn object after the file download) ?
    Alternatively, how to launch a background task that has the ‘Conn’ so it can carry out a file download asynchronously?
  2. Assuming the redirect approach, does it matter if I redirect to a Phoenix controller that is setup via pipe_through :api or :browser in router.ex?
  3. (Bonus points) Is there a way to be notified when the file has been downloaded? I’ve like to put a flash message on the screen, if possible. With the background process, I was thinking Async.await() could be used. For the send_download from Controller approach, I have no idea how to know when the download has finished.

Thanks for reading!

Most Liked

evadne

evadne

Sorry, old code follows, this has worked for 10+ years:

jQuery('<iframe>').attr('src', file.url).hide().appendTo(jQuery(document.body))

So let’s adapt it to modern JS / LV interop with this in the body:

window.addEventListener(`phx:download`, (event) => {
  let uri = event.uri;
  let frame = document.createElement("iframe");
  frame.setAttribute("src", response.uri);
  frame.style.visibility = 'hidden';
  frame.style.display = 'none';
  document.body.appendChild(frame);
});

Then from the LiveView you use push_event at the appropriate juncture (name of event, would be download in this case, and it would have the URI) — win/win solution, no redirection (so you keep the LV running), the download proceeds via the same authentication system you have used (as it will go through a known set of Plugs), and the file is downloaded!! Plus this would work nice with things you have to stream (such as via Packmatic etc)

Would recommend reading JavaScript interoperability — Phoenix LiveView v1.2.5 thoroughly.

PS: Could also use a phx-ignore container to hang your iframe in, or just make some space for it in your layout where LV would not touch, all depending on how your app is set up

PS 2: Redirecting away from a LV to something with content-disposition that is not inline probably causes what @ppiechota is seeing. So avoiding full redirection (you can’t get back easily, anyway) or anything that would cause the LV to stop running, would be key here.

12
Post #7
Miserlou

Miserlou

Simplest solution for small dynamic content to be saved as files:

{:noreply,
  socket |> push_event("download-file", %{
    text: "Your file contents",
    filename: "#{:os.system_time(:millisecond)}.txt"
})

and on a Hook:

    this.handleEvent("download-file", (event) => {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(event.text));
        element.setAttribute('download', event.filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
      });
mcrumm

mcrumm

Phoenix Core Team

@abbyjones @ppiechota @GeorgeMiller The server-side redirect is definitely the issue. If you redirect on the server, then the LiveView process shuts down. However since the download redirect does not change the browser document’s location, the (now disconnected) LiveView page is still accessible to the end-user.

I like @evadne’s solution if you want to force the download to start automatically. Generally I prefer to just render a download link. If the response sends content-disposition: attachment;... then everything else Just Works™.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
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
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
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New

Other popular topics Top

malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39523 209
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36432 110
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
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement