ruby-on-rails - 回形针:PDF 缩略图在 S3 上有错误的 content_type

标签 ruby-on-rails ruby amazon-s3 paperclip

我在 Rails 应用程序中使用 Paperclip 2.3.5 在 Amazon S3 上存储 PDF 文档。 ImageMagick 为每个 PDF 生成一个 JPG 缩略图。我在模型中使用此配置:

has_attached_file :file,
                  :styles => { :thumb => { :geometry => "200x200>",
                                           :format => :jpg
                                         } },
                  :whiny => false,
                  :storage => :s3,
                  :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
                  :s3_permissions => 'authenticated-read',
                  :s3_headers => { 'Expires' => 1.year.from_now.httpdate },
                  :url => "s3.amazonaws.com",
                  :path => "documents/:id/:style/:basename.:extension",
                  :bucket => 'mybucket'

但有一个问题:生成的缩略图上传到 S3 的内容类型为“application/pdf”,这是错误的,因为它是 JPG(您可以使用 Cyber​​duck 等 S3 探索工具查看 S3 上文件的内容类型).对于原始 PDF 文件,此 content_type 是正确的,但对于缩略图则不正确。这会在某些不显示内联缩略图的浏览器(例如 Chrome 或 Safari)中造成问题。

注意:存储在我的数据库(字段“file_content_type”)中的 content_type 是“application/pdf”,它仍然是正确的,因为它是原始文件的 content_type。

如果缩略图与原始文件不同,我如何覆盖缩略图的 content_type?

最佳答案

这就是我们在 brighterplanet.com/research 上修复它的方式,其中有 pdf 文档和 png 预览:

has_attached :pdf_document,
  :storage => :s3,
  # [... other settings ...]
  # PDFs work better in Windows 7 / IE if you give them content-type: attachment
  :s3_headers => { 'Content-Disposition' => 'attachment' },
  :styles => { :preview => { :geometry => '135',  :format => :png } }

after_save :fix_thumbnail
def fix_thumbnail(force = false)
  # application/pdf and application/x-pdf have both been seen...
  return unless force or pdf_document_content_type.include?('pdf')

  # set content type and disposition
  s3 = AWS::S3.new(YAML.load(File.read("#{RAILS_ROOT}/config/aws_s3.yml")))
  t = s3.buckets[PAPERCLIP_BUCKET].objects[pdf_document.path(:thumbnail)]
  content = t.read
  t.write(:data => content, :content_type => 'image/png', :content_disposition => 'inline', :acl => :public_read)

  nil
end

关于ruby-on-rails - 回形针:PDF 缩略图在 S3 上有错误的 content_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203279/

相关文章:

android - AWS S3DownloadTask 无法解析主机 : No address associated with hostname

ruby-on-rails - Rails 中有条件地更改 link_to 位置的简洁方法

node.js - 我们可以直接从 url 上传图像到亚马逊 S3

java - 如何在 AWS Java SDK v2 Apache 客户端上设置代理

具有多个选项的 Ruby 字符串替换

jquery - 将 Javascript 变量传递给 Rails 部分

ruby - 如何在 Debian Linux for ARM 上运行 pry

ruby-on-rails - RoR - "A Server is already running"- 我如何杀死正在运行的服务器?

javascript - Jquery AJAX 调用未找到 Rails 路线

ruby-on-rails - 使用 rails :undefined method `register_engine' for nil:NilClass (NoMethodError) 尝试 angularjs 时出错