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:
- 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? - 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?
- (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
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.
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
@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™.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









