如何创建下载链接 [英] How to Create Download Link
问题描述
创建下载链接的最佳方式是什么?还有比下面更好的方法吗?
What's the best way to create a download link? Is there a better way than the following?
我正在考虑使用 link_to "Download", :controller =>..., :action =>...", :id => ...
在视图中.
I was thinking of using link_to "Download", :controller => ..., :action => ...", :id => ...
in the view.
添加 match/documents/download/:id =>文档#download
到 routes.rb
Adding match /documents/download/:id => documents#download
to routes.rb
在控制器中:
def download
send_file ...
end
此外,如果可能,我希望用户与链接保持在同一页面上.
Also, I'd like, if possible, for the user to remain on the same page as the link.
谢谢.
推荐答案
我将下载操作添加为资源块中的安静路由.这是我的典型代码:
I add the download action as a restful route in a resources block. Here's typical code for me:
routes.rb
resources :things do
member do
get :download
end
end
型号:
has_attached_file :document,
:path => ':rails_root/assets/documents/:id/:basename.:extension'
attr_protected :document_file_name, :document_content_type, :document_file_size
控制器:
def download
send_file @thing.document.path, :type => 'application/pdf', :filename => @thing.permalink
end
查看:
<%= link_to 'Download', download_thing_path(@thing) %>
这使用户保持在同一页面上,并使用我建议的名称启动下载(我使用固定链接).
This keeps the user on the same page, and just initiates the download with my suggested name (I use permalink).
动态生成是什么意思?它们是由您上传还是由您的应用程序动态创建的?
What do you mean by dynamically generated? Are they uploaded by you or created by your application on the fly?
这篇关于如何创建下载链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!