【问题标题】:Show PDF in Ruby on Rails assets在 Ruby on Rails 资产中显示 PDF
【发布时间】:2016-09-09 19:18:13
【问题描述】:

尝试通过链接到 www.testsite.com/documents/sample.pdf 的 URL 来显示 pdf

我正在使用回形针上传 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)}

我也在使用gem 'friendly_id',这样我就可以使用描述和名称搜索我上传的 sample.pdf 文件实例。

当进入该页面时(http://localhost:3000/documents/sample.pdf),我得到:
Missing template /document with {:locale=>[:en], :formats=>[:pdf], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}
我猜它与:formats=>[:pdf] 有关。

当我创建 <%= link_to "document", asset_path(document.file.url) %> 时,我得到了这个链接:
http://localhost:3000/Users/user/Desktop/testsite/documents/sample.pdf?1473447505
我希望更像:
http://localhost:3000/documents/sample.pdf

我的路线文件:

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

我不确定我是否会以正确的方式进行处理。

任何建议都会很棒。

【问题讨论】:

  • 你能分享你的路线文件吗?
  • @Udaykumardas 我已经为您提出了问题的要点。但我基本上只是将该文件包含在一个名为Document 的类中。 Document:name, :description, :file,:slug。 :file 被上传到assets/documents/ 位置的文件夹中。这是我想访问pdf的地方,但使用如下网址:www.testsite.com/documents/sample.pdf

标签: ruby-on-rails pdf asset-pipeline friendly-id


【解决方案1】:

更改链接

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

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

然后在documents_controller.rb中

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

如果它要求下载 PDF 文件,请检查此问题

Forcing the inline rendering of a PDF document in Rails

【讨论】:

  • 这完美!文档控制器部分是我真正苦苦挣扎的地方,谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 1970-01-01
相关资源
最近更新 更多