使用 gem 回形针下载文件

Download file using gem Paperclip

我想了解如何使用 Paperclip 下载文件。我上传文件到本地存储。

型号:

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

这是风景 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 %>

我喜欢这样: File download using Paperclip 但它没有帮助。

但是当我点击下载时,出现错误: 没有路由匹配 [GET] "/public/attach/text.txt"

如何解决这个问题?为什么点击"Download"无法下载文件?

Rails 将 /public 目录放在服务器的 Web 根目录中。因此,文件系统路径为 /public/foo.txt 的文件可以在 http://localhost:3000/foo.txt 访问,而不是 http://localhost:3000/public/foo.txt.

因此您需要更改附件的 url 选项:

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

我下载文件的解决方案是这样的:

<%= link_to 'Download', @afile.attach.url(:original),
    download: @afile.attach.url(:original)%>