Download attachement using Phoenix LiveView

Hi everyone,
I have recently started deep dive into Phoenix LiveView, I have not found a LiveView approach to download a document from a LiveView template

Goal: - I have a list that shows the name of the documents, on clicking any name I want to fetch the stored location( path of the S3 )from the database and prepare a presigned URL with an expiration on it which can be used to download.

The approach I have figured is to on-click of the document name, redirect to a Phoenix route then return something like

    conn 
    |> put_resp_header("content-disposition", 
                       ~s(attachment; filename="#{filename}"))
    |> send_file(200, filename)

Is there any LiveView approach to implement it ??
Any reference to the document or example link will be helpful.
Thanks in advance.

Have you had a look at the presigned_url function of the aws_s3 package? You can create a helper of some sort and then just put an a tag in your template, no need to do anything live view specific, something like:

<a href={FileHelper.generate_url_for_file(@socket, @something.file_location)} download={FileHelper.generate_url_for_file(@socket, @something.file_location)}>
 Download file
</a>

the helper function would look something like:

def generate_url_for_file(socket, file_location) do
  ExAws.Config.new(:s3)
  |> ExAws.S3.presigned_url(:get, @bucket, file_location, expires_in: 300)
  |> case do
    {:ok, url} -> url
    # if something goes wrong, just return a blank link
    _ -> "#"
  end
1 Like