简体   繁体   English

使用gem回形针下载文件

[英]Download file using gem Paperclip

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 : 它是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. 我确实喜欢这样: 使用Paperclip下载文件,但没有帮助。

But when i click on the Download, then an error: No route matches [GET] "/public/attach/text.txt" 但是,当我单击“下载”时,出现一个错误: 没有路由与[GET]“ / public / attach / text.txt”匹配

How to solve this problem? 如何解决这个问题呢? Why file cannot be downloaded by clicking "Download"? 为什么无法通过单击“下载”来下载文件?

Rails places the /public directory in the servers web root. Rails将/public目录放置在服务器Web根目录中。 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 . 因此,具有文件系统路径/public/foo.txt的文件将可以通过http://localhost:3000/foo.txt而不是http://localhost:3000/public/foo.txt

So you need to change url option for the attached file: 因此,您需要更改附件文件的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

My solution to download file is something like : 我下载文件的解决方案是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM