'Rails upload a file - temporary file path needs file extension

I have an app that generates a PDF from react-pdf/renderer. Then the PDF is saved to ActiveStorage (utilizing Amazon S3). Some of the PDFs are too large though, due to the large number of pictures. So, before saving to ActiveStorage, I want to compress the PDF, and then save the compressed version to ActiveStorage.

Currently, this is working:

record.pdf.attach(io: URI.open(params[:pdf]), filename: "#{record.name}.pdf")

But as I mentioned, if the PDF is super large, I want to compress before this.

I am currently trying the gem ilovepdf

It suggests sending a PDF like this for compression:

file1 = task.add_file 'my_disk/my_example1.pdf'

So if I receive the PDF as a temporary file like this, how do I send the PDF?

`Parameters: {"id"=>"31", "pdf"=>#<ActionDispatch::Http::UploadedFile:0x00000001184be1c8 @tempfile=#<Tempfile:/var/folders/49/y1gcfxyn1w5gvbg3gcvpt2k40000gn/T/RackMultipart20211207-20325-xopriz>, @original_filename="Last Catalog", @content_type="application/pdf", @headers="Content-Disposition: form-data; name=\"pdf\"; filename=\"Last Catalog\"\r\nContent-Type: application/pdf\r\n">}`

It seems I should be able to send the temp file's path like this:

file = my_task.add_file params[:pdf].tempfile.path

But it gives the error

Ilovepdf::Errors::UploadError ([UploadError] Request can't be processed successfully Details: {"file"=>["File extension  not supported."], "type"=>["InvalidExtension"]}):

params[:pdf].tempfile.path looks like this:

/var/folders/49/y1gcfxyn1w5gvbg3gcvpt2k40000gn/T/RackMultipart20211207-20325-swnjp1

It seems like the error is indicating that it expects to see '.pdf' at the end of the file name. Is there a way to force that, or re-save a temp file with a file extension? Is there an easier way to compress the PDF before saving to ActiveStorage?



Solution 1:[1]

Use my_task.add_file params[:pdf].tempfile.path.to_s

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1