0

I want to understand how to download file using Paperclip. I upload file to local storage.

It's Model:

class AFile < ActiveRecord::Base
  has_attached_file :attach,
  :url => "public/attach/:basename.:extension",
  :path => ":rails_root/public/attach/:basename.:extension"
  validates_attachment_content_type :attach, content_type: "text/plain"
end

It's View show.html.erb :

<p>
  <strong>AFile:</strong>
  <%= @afile.name_file %>
</p>

<%= link_to 'Download', @afile.attach.url(:original, false) %> |
<%= link_to 'Edit', edit_afile_path(@afile) %> |
<%= link_to 'Back', afiles_path %>

I did like this: File download using Paperclip but it did not help.

But when i click on the Download, then an error: No route matches [GET] "/public/attach/text.txt"

How to solve this problem? Why file cannot be downloaded by clicking "Download"?

Community
  • 1
  • 1
Artur Olenberg
  • 508
  • 1
  • 5
  • 16

2 Answers2

2

Rails places the /public directory in the servers web root. So a file with the file system path /public/foo.txt will be accessible at http://localhost:3000/foo.txt - not http://localhost:3000/public/foo.txt.

So you need to change url option for the attached file:

class AFile < ActiveRecord::Base
  has_attached_file :attach,
  :url => "/attach/:basename.:extension",
  :path => ":rails_root/public/attach/:basename.:extension"
  validates_attachment_content_type :attach, content_type: "text/plain"
end
max
  • 96,212
  • 14
  • 104
  • 165
  • PS. The singular form is `attachment` - `attach` is a verb. I would name the class `Attachment` or `Upload` and `has_attached_file :file`. `AFile` is a really poor model name when it comes to pluralization. – max Dec 27 '15 at 13:37
  • already have good changes! Now i have :url => "/attach/:basename.:extension" and error "no routes..." disappeared! Now, the browser displays the contents of the file. To file downloaded after clicking "Download" I should write a method to download and make changes to routes.rb? – Artur Olenberg Dec 28 '15 at 05:03
  • Yes you would create a route and a controller. Use send_file to send the file as the payload in the response. – max Dec 28 '15 at 12:31
  • Thank you, you really helped me! – Artur Olenberg Dec 28 '15 at 12:48
-1

My solution to download file is something like :

<%= link_to 'Download', @afile.attach.url(:original),
    download: @afile.attach.url(:original)%>
Draken
  • 3,134
  • 13
  • 34
  • 54