Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

file download link in rails

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...