18

I am using Rails to make a small file upload app. For file attachment I am using the wonderful Paperclip but I can't work out how to do downloads.

How would I create a link in my show view, that is passed the file id, for instance that would allow the user to download a file on my server?

seadowg
  • 4,215
  • 6
  • 35
  • 43

2 Answers2

34

If the file uploaded is attached to a model, e.g. as an attribute called avatar, then you can create a link like:

<%= link_to "Download", model.avatar.url(:original, false) %>

Replace avatar with the name of your attribute.

Community
  • 1
  • 1
Syed Aslam
  • 8,707
  • 5
  • 40
  • 54
  • Could you give an example of what might replace "whatever" ? For example I have a DBFiles model ... but there is no method .url for this model... – carl crott Sep 19 '12 at 00:17
  • The whatever would be your "file", "avatar" or whatever you called the file property on your model. So "aUserElement.avatar.url(:original, false)" for instance. – Automatico Jun 10 '13 at 20:29
  • 9
    what does original:false mean? – Jwan622 Apr 23 '15 at 03:09
  • Using parameters of `:original, false` tells Paperclip to send the original-sized file (first parameter) and `false` (second parameter) tells it to _not_ include the timestamp on the URL. – Mike Gorski Nov 15 '19 at 20:21
  • This generates a link for me, to open the file in browser itself, if possible. If you want to explicitly download, I had to add an extra HTML attribute of download. So, my final code was - `<%= link_to "Download", model.avatar.url(:original, false), :download => '' %>`. Ref - https://developers.google.com/web/updates/2011/08/Downloading-resources-in-HTML5-a-download – nilshah98 Oct 08 '21 at 20:20
1

Replace whatever by name that are user in your model for paper clip if you have

resource_file_name, resource_file_name, resource_file_name,

then replace whatever by resource

Thorin
  • 2,004
  • 1
  • 19
  • 30