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

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);
      });
10 Likes