Rails从show动作下载文件?

我有一个上传器,允许您上传文件。 我想要做的是在您查看其show动作时触发文档下载。 url将是这样的:

/documents/16 

该文档可以是.txt或.doc。

到目前为止,我的show动作看起来像这样:

  def show @document = Document.find(params[:id]) respond_with(@document) do |format| format.html do render layout: false, text: @document.name end end end 

我该如何实现这一目标?

看一下send_data方法:

将给定的二进制数据发送到浏览器。 此方法类似于render:text => data,但也允许您指定浏览器是否应将响应显示为文件附件(即在下载对话框中)或内联数据。 您还可以设置内容类型,表观文件名和其他内容。

所以,我认为在你的情况下它应该是这样的:

 def show @document = Document.find(params[:id]) send_data @document.file.read, filename: @document.name end 

我在控制器中创建了一个用于下载文件的新方法。 看起来像这样。 Stored_File是已归档文件的名称,并且有一个名为stored_file的字段,该字段是文件的名称。 使用Carrierwave,如果用户具有下载文件的访问权限,则会显示URL,然后使用send_file将文件发送给用户。

调节器

  def download head(:not_found) and return if (stored_file = StoredFile.find_by_id(params[:id])).nil? case SEND_FILE_METHOD when :apache then send_file_options[:x_sendfile] = true when :nginx then head(:x_accel_redirect => path.gsub(Rails.root, ''), :content_type => send_file_options[:type]) and return end path = "/#{stored_file.stored_file}" send_file path, :x_sendfile=>true end 

视图

 <%= link_to "Download", File.basename(f.stored_file.url) %> 

路线

 match ":id/:basename.:extension.download", :controller => "stored_files", :action => "download", :conditions => { :method => :get }