Phoenix file download

Hey guys,

In my application I need to introduce file download functionality. I can’t figure out how to achieve that in Phoenix. I have little experience with web development so maybe someone here could share his knowledge or ideas. These files are created dynamically throughout application lifetime. For now I would like to store files locally and not use external services like S3.

Thanks in advance! :slight_smile:

4 Likes

Hello @zsuidakra, I can show you a code snippet from a project of mine where I let the users download files both from a local directory in the machine and from an external service (Amazon S3 and Google Cloud Storage):

 def get_attachment(conn, ticket_attachment_id) do 
    attachment = Repo.get(TicketAttachment, ticket_attachment_id) 
    filename   = attachment.attachment_url |> String.split("/") |> List.last
    {_, 0}     = download_attachment attachment.attachment_url

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

    {_, 0} = System.cmd "rm", [filename]
  end

I’m not really versed in http and Web applications so I can’t explain the reasoning behind it.

6 Likes

@sashaafm thanks, I must have missed send_file/5 somehow. Can you please explain what does download_attachment/1 function do?

2 Likes

Yes it transfers through sftp the requsted file from another machine in the same network:

defp download_attachment(attach_url) do 
    {_, 0} = System.cmd "sftp", ["#{@username}@#{@server}:#{attach_url}"]
  end
3 Likes

Okay, thank you for help :slight_smile:

2 Likes

You might also look at scarab, self-described as: content-addressable file storage for elixir

It supports both S3 (AWS) and FS (Local Filesystem) and you can always make your own as well.

3 Likes

Another possible app is arc.

3 Likes

Wow, I wasn’t looking for upload support, but this looks great, it will help me cut on a lot of boilerplate code :slight_smile:

I think that arc mentioned by @sashaafm is more suitable for my needs :slight_smile:

1 Like

Just released a library for downloads only: https://github.com/asiniy/download

1 Like