简体   繁体   English

在Ruby on Rails资产中显示PDF

[英]Show PDF in Ruby on Rails assets

Trying to show a pdf by linking to a URL of www.testsite.com/documents/sample.pdf 尝试通过链接到www.testsite.com/documents/sample.pdf的URL来显示pdf

I'm using paperclip to upload the pdf, and can see that the pdf is there. 我正在使用回形针上传pdf,并且可以看到pdf在那里。

    has_attached_file :file,
    :url => ":rails_root/documents/:filename",
    :path => ":rails_root/public/assets/documents/:id/:filename"

    validates_attachment :file, :content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}

I'm also using the gem 'friendly_id' so that I can search my uploaded instance of the sample.pdf file with the description and name. 我还使用了gem 'friendly_id'以便可以使用说明和名称搜索我上载的sample.pdf文件实例。

When entering that page( http://localhost:3000/documents/sample.pdf ) though, I get: 当进入该页面( http://localhost:3000/documents/sample.pdf )时,我得到:
Missing template /document with {:locale=>[:en], :formats=>[:pdf], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}
I'm guessing it has something to do with the :formats=>[:pdf] . 我猜想它与:formats=>[:pdf]

When I create a <%= link_to "document", asset_path(document.file.url) %> , I get this link: 当我创建<%= link_to "document", asset_path(document.file.url) %> ,我得到以下链接:
http://localhost:3000/Users/user/Desktop/testsite/documents/sample.pdf?1473447505
Which I would like to be more like: 我想更像是:
http://localhost:3000/documents/sample.pdf

My Routes file: 我的路线文件:

Rails.application.routes.draw do
  resources :documents
  root 'main_pages#home'
  get 'home' => 'main_pages#home'
  get '*path' => redirect('/')
end

I'm not sure if I'm going about this the right way at all. 我不确定是否要以正确的方式进行操作。

Any suggestions would be great. 任何建议都很好。

Change your link 改变你的链接

<%= link_to "document", asset_path(document.file.url) %>

To

<%= link_to "document", document_path(document) %>

Then in documents_controller.rb 然后在documents_controller.rb中

def show
  send_file(document.file.url, :filename => "your_document.pdf", :disposition => 'inline', :type => "application/pdf")
end

Check this question in case it asks to download the PDF file 如果要求下载PDF文件,请检查此问题

Forcing the inline rendering of a PDF document in Rails 在Rails中强制内联渲染PDF文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM