gpt4 book ai didi

ruby-on-rails - 使用 Prawn 和 Carrierwave 上传 PDF 而不将文件保存在磁盘上

转载 作者:行者123 更新时间:2023-12-02 00:25:04 28 4
gpt4 key购买 nike

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

发票.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 方法来实际创建文件,但是这个文件保存在我的应用程序的根文件夹中,所以我需要在之后删除它。有没有更好的办法?有没有办法在不实际将文件保存在磁盘上的情况下附加文件?

最佳答案

您要归档的内容确实令人印象深刻。谢谢你的想法。这将减少 PDF 生成中与磁盘 IO 相关的大量问题。

第一名:Renders the PDF document to a string

使用返回 PDF 字符串表示形式的 Prawn::Document#render 方法代替 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

关于ruby-on-rails - 使用 Prawn 和 Carrierwave 上传 PDF 而不将文件保存在磁盘上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042417/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com