文件下载链接在rails [英] file download link in rails
问题描述
我想给访问者下载一些pdf的选项。
我试过:
<%= link_toabc,/data/abc.pdf\"% >
<%= link_toabc,/data/abc.pdf,:format => 'pdf'%>
和一些变体,但似乎不起作用。我继续获得没有路线匹配[GET]/data/abc.pdf
我有pdf文件在名为data的文件夹中,位于资产文件夹中。
任何帮助将不胜感激。
Rails 4:
路线:
gethome / download_pdf
$控制器(已经有pdf)的$ c $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ code> def download_pdf
send_file(
#{Rails.root} /public/your_file.pdf,
filename:your_custom_file_name.pdf,
type:应用程序/ pdf
)
end
在控制器中(需要生成pdf ):
requireprawn
class ClientsController< ApplicationController
def download_pdf
client = Client.find(params [:id])
send_data generate_pdf(client),
filename:#{client.name} .pdf,
类型:application / pdf
end
private
def generate_pdf(client)
Prawn :: Document $ new
text client.name,align::center
textAddress:#{client.address}
textEmail:#{client.email}
end.render
end
end
在视图中:
<%= link_to'下载PDF',home_download_pdf_url%>
Rails 3
执行方式:
def下载
send_data pdf,
:filename => ; abc.pdf,
:type => application / pdf
end
你应该去这个替代
Rails< 3
公开文件夹中的文件
您应该将文件放在公用文件夹中,这就是诀窍。
如果文件放置正确,应该工作。
如果您无法将文件移动到公用文件夹,请告知我。
通过控制器下载
创建一个带有downlaod操作的控制器, link_to
它
def下载
send_file'/assets/data/abc.pdf',:type => ;application / pdf,x_sendfile => true
end
I would like to give visitors the option to download some pdf. I have tried:
<%= link_to "abc", "/data/abc.pdf"%>
<%= link_to "abc", "/data/abc.pdf", :format => 'pdf' %>
and some variations but they don't seem to work. I keep getting No route matches [GET] "/data/abc.pdf"
I have the pdf files in a folder called data, located in the assets folder. Any help would be appreciated.
Rails 4:
in routes:
get "home/download_pdf"
in controller (already have pdf):
def download_pdf
send_file(
"#{Rails.root}/public/your_file.pdf",
filename: "your_custom_file_name.pdf",
type: "application/pdf"
)
end
in controller (need to generate pdf):
require "prawn"
class ClientsController < ApplicationController
def download_pdf
client = Client.find(params[:id])
send_data generate_pdf(client),
filename: "#{client.name}.pdf",
type: "application/pdf"
end
private
def generate_pdf(client)
Prawn::Document.new do
text client.name, align: :center
text "Address: #{client.address}"
text "Email: #{client.email}"
end.render
end
end
in view:
<%= link_to 'Download PDF', home_download_pdf_url %>
Rails 3
The way to do it:
def download
send_data pdf,
:filename => "abc.pdf",
:type => "application/pdf"
end
You should go to this alternative
Rails < 3
File in public folder
This may the the answer to you: How to download a file from rails application
You should place your file in public folder, that is the trick.
Should work when the file is placed correctly.
Let me know if you can't move your file to public folder.
Download via controller
Create a controller with a downlaod action and link_to
it
def download
send_file '/assets/data/abc.pdf', :type=>"application/pdf", :x_sendfile=>true
end
这篇关于文件下载链接在rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!