【问题标题】:Uploading PDF with Prawn and Carrierwave without saving the file on disk使用 Prawn 和 Carrierwave 上传 PDF 而不将文件保存在磁盘上
【发布时间】:2019-01-04 16:06:15
【问题描述】:

我在后台作业中为发票生成 PDF 文件,我想将其附加到发票上。我使用 Carrierwave 进行文件上传,但在这里我不从 UI 上传它。我希望能够附加文件而不将其保存在磁盘上。

invoice.rb

mount_uploader :file, InvoiceFileUploader

后台工作

class GeneratePdfJob < ApplicationJob
  queue_as :default

  def perform(invoice)
    pdf = InvoiceServices::PdfGenerator.new(invoice)
    file_name = [invoice.number.gsub('/','-'), invoice.due_date.to_s, SecureRandom.urlsafe_base64].join('-') + '.pdf'
    pdf.render_file(file_name)
    file = File.new(file_name)
    invoice.file = file
    File.delete(file_name)
  end
end

所以现在我调用render_file 方法来实际创建文件,但是这个文件保存在我的应用程序的根文件夹中,所以我需要在之后删除它。有没有更好的办法?有没有办法在不实际保存在磁盘上的情况下附加文件?

【问题讨论】:

    标签: ruby-on-rails prawn


    【解决方案1】:

    您尝试归档的内容确实令人印象深刻。谢谢你的主意。这将减少 PDF 生成中许多与磁盘 IO 相关的问题。

    第一个:Renders the PDF document to a string

    使用返回 PDF 字符串表示形式的 Prawn::Document#rendermethod 代替 render_file 方法。

    第二个:use that string to upload to carrier wave without any tempory file.

    # define class that extends IO with methods that are required by carrierwave
    class CarrierStringIO < StringIO
      def original_filename
        "invoice.pdf"
      end
    
      def content_type
        "application/pdf"
      end
    end
    
    class InvoiceFileUploader < CarrierWave::Uploader::Base
      def filename
        [model.number.gsub('/','-'), model.due_date.to_s, SecureRandom.urlsafe_base64].join('-') + '.pdf'
      end
    end
    
    class Invoice
      mount_uploader :file, InvoiceFileUploader
    
      def pdf_data=(data)
        self.file = CarrierStringIO.new(data)
      end
    end
    
    class GeneratePdfJob < ApplicationJob
      queue_as :default
    
      def perform(invoice)
        pdf = InvoiceServices::PdfGenerator.new(invoice)        
        invoice.pdf_data = pdf.render
      end
    end
    

    【讨论】:

    • 太棒了!奇迹般有效!会给你送一托盘啤酒;)
    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 2018-09-14
    • 2011-12-25
    • 2013-12-26
    • 2019-10-30
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多