从延迟作业到上传者的文件

时间:2014-11-24 22:35:22

标签: ruby-on-rails pdf file-upload amazon-s3 carrierwave

我正在尝试获取此PDF,我是通过上传器(使用CarrierWave)上传到s3的延迟作业创建的。现在我将PDF保存到tmp文件夹中,就像测试一样(并且它可以工作)。我已经安装了我的订单模型,在我的订单表上创建了一个收据属性,我想将路径名存储到s3。无论如何,问题是,我如何将此PDF文件传输到上传器?任何帮助表示赞赏!

我在order_controller中调用它

Delayed::Job.enqueue PdfReceiptJob.new(@order.id)

延迟工作的代码。请注意,它现在将其保存到tmp文件夹。

class PdfReceiptJob < Struct.new(:order_id)

        def perform

            order = Order.find(order_id)

            # create an instance of ActionView, so we can use the render method outside of a controller
            view = ActionView::Base.new(ActionController::Base.view_paths, {})
            html_template = view.render(file: "order/receipt_attachment.html.erb", locals:{order:order})

            # use wicked_pdf gem to create PDF from the HTML receipt template
            pdf_receipt = WickedPdf.new.pdf_from_string(html_template, :page_size => 'Letter')

            # save PDF to disk. Later, to be stored in fog, sent to S3, than saved back to our DB
            pdf_path = Rails.root.join("tmp", "marmoset-receipt#{order.id}.pdf") #ex: will be at tmp/marmoset-receipt215.pdf

            File.open(pdf_path, 'wb') do |file|
            file << pdf_receipt
            end

        end
    end

上传代码,到目前为止:

class ReceiptUploader < CarrierWave::Uploader::Base

  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/marmoset-receipt#{model.id}"
  end

  #set headers for pdf file 
  def fog_attributes
    {'Content-Disposition' => "attachment;"}
  end

  # Add a white list of extensions which are allowed to be uploaded.
  def extension_white_list
    %w(pdf)
  end


end

1 个答案:

答案 0 :(得分:0)

听起来你有这样的模特:

class Order < ActiveRecord::Base
  mount_uploader :receipt, ReceiptUploader
end

因此,在PdfReceiptJob perform功能结束时,您应该可以添加以下内容:

order.receipt = File.open(pdf_path)
order.save!