简体   繁体   中英

How to give the xls file link in Ruby on Rails?

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"

when i given above link that is converting like this

 <a href="//home/kiran/shekar/wavespot/public/reports/10014_ByNetwork.xls" target="_blank">Excel</a>

So its not working. actually i need like this

<a href="file:///home/kiran/shekar/wavespot/public/reports/10014_ByNetwork.xls" target="_blank">Excel</a>

Please give me exact path...

@Gagan Your syntax is incorrect. You should test your answers before posting them. This is the correct way:

<%= link_to 'Excel',"/reports/10014_ByNetwork.xls", target: "_blank" %>

OR

<%= link_to 'Excel',"/reports/10014_ByNetwork.xls", :target=>"_blank" %>

You have missed out the comma after the second closing double quotes.

Are you sure that you need file:// link? It is not operated by rails server and will work only on your machine. Maybe it will be better to generate link like this: " http://you_server_url.org/public/file.xml ". It works fine on local and remote app, and you can manage file-sending by controller action.

在您的视图文件中尝试以下操作:

<%= link_to 'Excel',"/reports/10014_ByNetwork.xls" :target=>"_blank" %>

if you have more than one file to download and you have to use different links along your views I could recommend you the next approach too:

Add a download xls get resource and route helper to your routes.rb file like:

get "downloads/xls/:id" => "downloads#xls", :as => :download_xls

In your controller, for my my example I'll use app/controllers/downloads_controller.rb we will need to add the xls action to stream data with 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

You can read more about it here: http://apidock.com/rails/ActionController/DataStreaming/send_file

And finally in your view you'll use the link_to helper with our declared above download_xls_path route and the filename as param:

<p>
  Click to download: </br> 
  <%= link_to "NameOfYourXlsFile.xls", download_xls_path(NameOfYourXlsFile) %>
</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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