我已经打了一段时间了,你的帮助肯定会非常值得赞赏。
我已经建立了一种签署pdf文档的方法,您可以找到here,现在离签名文件只有一步之遥。
我想以异步方式执行此操作,但首先我需要了解如何同步执行此操作。
所以我尝试了两种不同的方法,post post_process:
after_post_process do |receipt|
if receipt.receipt_file_changed?
require 'aws-sdk'
logger.debug("RECEIPT ID: #{self.inspect}")
file = receipt.receipt_file.queued_for_write[:original]
s3=AWS::S3.new(
access_key_id: S3_CONFIG["access_key_id"],
secret_access_key: S3_CONFIG["secret_access_key"])
bucket_name = S3_CONFIG["bucket"]
b = s3.buckets[bucket_name]
filen = File.basename(file.path)
outputF = "original/teste.pdf"
o = b.objects[outputF]
o.write(file: file.path)
end
end
我希望能够将文件发送到类似/original/1/myfilename.pdf
的路径,其中1将是我的receipt_id(并且在post post_process之后为null)。
然后我尝试了一种与after_save不同的方法,但receipt_file.to_file(:original)不是有效的调用...
after_save do |receipt|
if receipt.receipt_file_changed?
require 'aws-sdk'
logger.debug("RECEIPT ID: #{receipt.inspect}")
s3=AWS::S3.new(
access_key_id: S3_CONFIG["access_key_id"],
secret_access_key: S3_CONFIG["secret_access_key"])
bucket_name = S3_CONFIG["bucket"]
b = s3.buckets[bucket_name]
filen = File.basename(receipt_file_file_name)
outputF = "original/teste.pdf"
o = b.objects[outputF]
o.write(file: receipt.receipt_file.to_file(:original))
end
end
如何获取文件并将其重新上传回S3?
修改
经过一些研究后,我阅读了如何从Amazon加载文件,现在问题是我的文件内容是空的......我做错了什么?
after_save do |receipt|
if receipt.receipt_file_changed?
require 'aws-sdk'
logger.debug("I was here inside after_save")
s3=AWS::S3.new(
access_key_id: S3_CONFIG["access_key_id"],
secret_access_key: S3_CONFIG["secret_access_key"])
bucket_name = S3_CONFIG["bucket"]
b = s3.buckets[bucket_name]
filen = File.basename(receipt_file_file_name)
logger.debug("Filename is #{filen}")
path = "original/#{receipt.id}/#{filen}"
o = b.objects[path]
require 'tempfile'
ext= File.extname(filen)
file = Tempfile.new([File.basename(filen,ext),ext], :encoding => 'ascii-8bit')
# streaming download from S3 to a file on disk
begin
o.read do |chunk|
file.write(chunk)
end
end
file.close
logger.debug("File is #{file.inspect}")
o.write(file: signPdf(file).path)
file.unlink
end
end
答案 0 :(得分:1)
将这个问题分成几部分之后,我注意到真正的问题是在下载和写入本地磁盘的过程中。所以我问了question,并找到了解决方法。 最后获得了以后保存的代码:
after_save do |receipt|
if receipt.receipt_file_changed? && !@receipt.receipt_file.url[".pdf"]
require 'aws-sdk'
s3=AWS::S3.new(
access_key_id: S3_CONFIG["access_key_id"],
secret_access_key: S3_CONFIG["secret_access_key"])
bucket_name = S3_CONFIG["bucket"]
b = s3.buckets[bucket_name]
filen = File.basename(receipt_file_file_name)
path = "original/#{receipt.id}/#{filen}"
o = b.objects[path]
require 'open-uri'
require 'tempfile'
ext= File.extname(filen)
tfile = Tempfile.new([File.basename(filen,ext),ext])
begin
open(tfile.path,"wb") do |file|
file << open(receipt.receipt_file.url,:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE).read
o.write(file: signPdf(file).path, :acl => :public_read)
end
ensure
tfile.close!
end
end
end