I've been fighting this for some time now, and your help will certainly be of much appreciation.
I've built a method to sign pdf documents which you can find here, and now am only one step away from signing my file.
I would like to do this asynchronously, but first i would need to understand how to do it synchronously.
So I try 2 different approaches, the after 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
where i wanted to be able to send the file to a path something like /original/1/myfilename.pdf
where 1 would be my receipt_id (and is null at the time of the after post_process).
I then tried a different approach with after_save, but receipt_file.to_file(:original) is not a valid call...
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
How can i get the file and upload it back again to S3 ?
Edit
After some research i read how we can load a file from Amazon, and now the problem is that my file content is empty...What am i doing wrong?
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
After splitting this problem in pieces, i noticed the real problem was within the process of download and writing to local disk. So i asked this question, and reached for a workaround. In the end got this code for the after save :