iroshiva
iroshiva

Reputation: 9

Download a PDF file with ruby-on-rails, error message

I followed the steps setting a link to download a PDF file on a preview question about that. Problem is, when I click on the download button, it open a window to show the PDF, but the PDF doesn't show up... When I open or download it, I got this message "File type unknown (application/octet-stream) is not supported"

What's wrong? Thank you

Here, how i set it up:

Controller

class HomesController < ApplicationController
  def index
  end

  def download_pdf
    send_file(
        "#{Rails.root}/app/assets/docs/dossier_de_presentation_lvsl.pdf",
        type: "application/pdf"
        x_sendfile: true
        )  
  end
end

routes.rb

get 'download_pdf', to: "homes#download_pdf"

view

<%= link_to "Download Pdf", "/assets/dossier_de_presentation_lvsl.pdf", :class => "themed_text", class: "btn btn-lg btn-custom" %>

Upvotes: 0

Views: 1262

Answers (1)

edariedl
edariedl

Reputation: 3352

Your controller action is not used at all. Browser tries to download file from the following path public/assets/dossier_de_presentation_lvsl.pdf.

If you want to download it through the controller action. You should set your application in following way:

In your routes:

get '/download_pdf', to: 'homes#download_pdf', as: 'download_pdf'

In your controller:

  def index
  end

  def download_pdf
    send_file(
        "#{Rails.root}/app/assets/docs/dossier_de_presentation_lvsl.pdf",
        type: "application/pdf",
        disposition: 'attachment', # 'inline' if you want to show PDF in the browser instead of downloading it directly
        x_sendfile: true
        )  
  end
end

In your view:

<%= link_to "Download Pdf", download_pdf_path(format: :pdf), :class => "themed_text", class: "btn btn-lg btn-custom" %>

Or if you want, you can put your PDF directly to public folder in your rails app eg. to public/pdf/dossier_de_presentation_lvsl.pdf

and than you can use just a link:

<a href="/pdf/dossier_de_presentation_lvsl.pdf" class="themed_text btn btn-lg btn-custom">Download PDF</a>

But you can use this only if your PDF can be downloaded by everyone without any authentication etc. On the other hand you would not have to bother with the controller action and routes, it will be handled for you automatically.

Upvotes: 3

Related Questions