Badops
Badops

Reputation: 91

How to download or save files locally in Phoenix

I figured a way to upload attachments locally using arc and arc_ecto. I however want to find a way where users of my application can download or save these uploaded files by just clicking on a download button on the browser. The downloaded files will be in a separate folder.

I have gone through many sources but I seem not to still get it.

Please how do I do this?

Upvotes: 3

Views: 5354

Answers (2)

Jagdish Narayandasani
Jagdish Narayandasani

Reputation: 772

def download_csv(conn, %{"id" => id}) do
  company = Repo.get!(Company, id)

  file = File.read!("files/#{company.id}.csv")

  conn
   |> put_resp_content_type("text/csv")
   |> put_resp_header(
    "content-disposition",
    "attachment; filename=\"#{company.id}.csv\"")
   |> send_resp(200, file)
  end
end

Upvotes: 6

Marian Bäuerle
Marian Bäuerle

Reputation: 371

Maybe this helps you: https://hexdocs.pm/phoenix/Phoenix.Controller.html#send_download/3

Sends the given file or binary as a download.

In a Phoenix controller call the function with the uploaded file's path.

To send a file that is stored inside your application priv directory:

path = Application.app_dir(:my_app, "priv/prospectus.pdf")
send_download(conn, {:file, path})

Upvotes: 7

Related Questions