rails中的文件下载链接 [英] file download link in rails
问题描述
我想让访问者选择下载一些 pdf.我试过了:
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' %>
和一些变体,但它们似乎不起作用.我不断收到 No route matching [GET] "/data/abc.pdf"
and some variations but they don't seem to work. I keep getting No route matches [GET] "/data/abc.pdf"
我将 pdf 文件放在名为 data 的文件夹中,该文件夹位于资产文件夹中.任何帮助将不胜感激.
I have the pdf files in a folder called data, located in the assets folder. Any help would be appreciated.
推荐答案
Rails 4:
在路线中:
get "home/download_pdf"
在控制器中(已经有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
在控制器中(需要生成pdf):
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
在视图中:
<%= link_to 'Download PDF', home_download_pdf_url %>
Rails 3
实现方式:
def download
send_data pdf,
:filename => "abc.pdf",
:type => "application/pdf"
end
你应该去这个选择
Rails <3
公共文件夹中的文件
这可能就是你的答案:如何下载文件来自 Rails 应用程序
您应该将文件放在公共文件夹中,这就是窍门.
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.
通过控制器下载
创建一个带有下载动作的控制器并link_to
它
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屋!