如何在Ruby on Rails中提供xls文件链接?
How to give the xls file link in ruby. This is my file path link_to "Excel", "/#{RAILS_ROOT}/public/reports/10014_ByNetwork.xls", :target=>"_blank"
当我给上面的链接转换像这样
Excel
所以它不起作用。 实际上我需要这样的
Excel
请给我一个确切的路径……
@Gagan您的语法不正确。 您应该在发布之前测试您的答案。 这是正确的方法:
<%= link_to 'Excel',"/reports/10014_ByNetwork.xls", target: "_blank" %>
要么
<%= link_to 'Excel',"/reports/10014_ByNetwork.xls", :target=>"_blank" %>
在第二次收盘双引号后你错过了逗号。
您确定需要file:// link吗? 它不由rails服务器操作,仅适用于您的计算机。 也许最好生成这样的链接:“ http://you_server_url.org/public/file.xml ”。 它适用于本地和远程应用程序,您可以通过控制器操作管理文件发送。
在您的视图文件中尝试此操作:
<%= link_to 'Excel',"/reports/10014_ByNetwork.xls" :target=>"_blank" %>
如果您要下载多个文件,并且必须在视图中使用不同的链接,我也可以向您推荐下一个方法:
添加下载xls get资源并将路径助手添加到routes.rb
文件中,如:
get "downloads/xls/:id" => "downloads#xls", :as => :download_xls
在你的控制器中,对于我的例子,我将使用app/controllers/downloads_controller.rb
我们需要添加xls动作来使用send_file
来传输数据:
def xls if params[:id] send_file("#{Rails.root}/public/reports/#{params[:id]}.xls", filename: "#{params[:id]}.xls", type: 'application/excel', disposition: 'attachment') end end
您可以在此处阅读更多相关信息: http : //apidock.com/rails/ActionController/DataStreaming/send_file
最后在您的视图中,您将使用link_to
帮助程序与我们声明的上面的download_xls_path
路由和文件名作为参数:
Click to download: <%= link_to "NameOfYourXlsFile.xls", download_xls_path(NameOfYourXlsFile) %>