WickedPDF生成的带有神社的PDF文件上传不会填充数据字段

时间:2019-03-02 13:02:42

标签: ruby-on-rails ruby-on-rails-5.2 shrine

我正在从Paperclip迁移整个升级过程,并且在生成PDF时遇到问题。

处理上传的子模型是名为quotepdf的多态模型

有时会生成一个quotepdf实例,并有一个链接到它的附件。

这是适用于神社的quotepdf模型

class Quotepdf < ApplicationRecord
  include QuotesAndInvoicesUploader::Attachment.new(:quote)    
  belongs_to :quotable, polymorphic: true

end

上传者:

class QuotesAndInvoicesUploader < Shrine
    plugin :validation_helpers # to validate pdf
    plugin :delete_raw

    Attacher.validate do
        validate_max_size 1.megabyte
        validate_mime_type_inclusion ['application/pdf']
    end

    def generate_location(io, context)
        type  = context[:record].class.name.downcase if context[:record]
           name  = super

        [type, name].compact.join("/")
      end

end

和使用Wickedpdf处理“ quotepdf记录”和PDF附件创建的Sidekiq工作人员:

class PhotographerQuotePdfWorker
  include Sidekiq::Worker
  sidekiq_options retry: false

  def perform(id)
    @quote = Photographerquote.find(id)
    ac = ActionController::Base.new()
    pdf_string = ac.render_to_string pdf: 'photographerquote-'+@quote.hashed_id.to_s, template: "photographerquote/print_quote.pdf.erb", encoding: "UTF-8", locals: {pdfquote: @quote}

    new_pdf = @quote.build_quotepdf
    new_pdf.quote = StringIO.new(pdf_string)
    new_pdf.save
  end

end

使用回形针可以正常工作。尽管带有神rine,但什么都没有保存到新的“ quotepdf”记录的“ quote_data”列中。 工人也没有返回错误。

确实将缓存文件上传到S3存储桶,因此可以正确生成PDF文件。最终文件丢失。

编辑

通过将我的上传器剥离为裸机来使其工作:

class QuotesAndInvoicesUploader < Shrine

    def generate_location(io, context)
        type  = context[:record].class.name.downcase if context[:record]
        name  = super 

        [type, name].compact.join("/")
    end

end

但是我不明白为什么以前失败:文件只有22KB,确实是PDF。不能是验证问题。.

编辑2

检测到的OK模仿类型确实为null

{"id":"devispdf/04aa04646f73a3710511f851200a2895","storage":"store","metadata":{"filename":null,"size":21613,"mime_type":null}}

尽管我的初始化器有Shrine.plugin :determine_mime_type

1 个答案:

答案 0 :(得分:1)

在您的后台工作中,尝试查看输出结果:

Shrine.determine_mime_type(StringIO.new(pdf_string))

如果它是nil,那么我建议您尝试使用其他分析仪(例如:mimemagic:marcel)。

Shrine.plugin :determine_mime_type, analyzer: :mimemagic
# or
Shrine.plugin :determine_mime_type, analyzer: :marcel

如果失败,您还可以使用基于扩展名的分析器,例如:mime_types:mini_mime,并在后台作业中分配带有扩展名的临时文件:

tempfile = Tempfile.new(["quote", ".pdf"], binmode: true)
tempfile.write pdf_string
tempfile.open # flush & rewind

new_pdf = @quote.build_quotepdf
new_pdf.quote = tempfile
new_pdf.save! # fail loudly if save fails

或者,由于您要附加在后台作业中,因此完全可以完全避免临时存储和验证:

pdf_file = StringIO.new(pdf_string)
uploaded_file = new_pdf.quote_attacher.store!(pdf_file)
new_pdf.quote_data = uploaded_file.to_json
new_pdf.save!