66

訪問者にpdfをダウンロードするオプションを提供したいと思います。私が試してみました:

<%= link_to "abc", "/data/abc.pdf"%>

<%= link_to "abc", "/data/abc.pdf", :format => 'pdf' %>

いくつかのバリエーションがありますが、機能していないようです。私は得続けますNo route matches [GET] "/data/abc.pdf"

assetsフォルダーにあるdataというフォルダーにpdfファイルがあります。どんな助けでも大歓迎です。

4

6 に答える 6

86

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
于 2012-10-31T18:13:46.397 に答える
23

ファイルが静的 (変更されないことを意味する) の場合は、パブリック フォルダーに配置します。

次に、次のようにダウンロードできます

<a href="file.pdf" download>PDF</a>

またはERBを使用

<%= link_to 'PDF', 'file.pdf', download: '' %>

ファイルにダウンロード用の別の名前を付けるには、その名前をダウンロードオプションに渡すだけです

<%= link_to 'PDF', 'file.pdf', download: 'data' %>

これにより、ファイルがdata.pdfではなくとしてダウンロードされますfile.pdf

于 2016-07-11T19:54:07.297 に答える