How to download generated file?


#1

Hello, I’m trying to make an endpoint that returns a generated PDF file. Any suggestions? I can’t figure out how to render a binary response. Alternatively I could save it to S3 and return an URL but I’m hoping it’s possible in memory.

Thanks!


#2

Have you tried setting the response headers? I’d guess that Content-Type: application/pdf would do it.


#3

Hi Nate, thanks for responding. I’m not familiar enough with the render function (in Jets or ActionView) to even get that far. I’ve tried

render pdf: pdf_contents

… with/without Content-Type, etc, but I just get “ActionView::MissingTemplate”, so clearly I’m not rendering the content correctly and it’s not setup with the right templates, etc. I’ve tried registering a handler for the pdf: symbol but didn’t get very far.


#4

I think this might help:
https://apidock.com/rails/v5.2.3/ActionController/DataStreaming/send_data


#5

Yeah, I’ve tried that already. It looks promising but the Jets controller doesn’t have that method defined. The controller doesn’t subclass the Rails one, but somehow implements a bunch of the logic, I suspect as an include. The controller just throws:

NoMethodError: undefined method `send_data’


#6

Maybe try render plain: or render text: and set the content type header manually.


#7

Awesome, that worked!

response.headers[‘Content-Disposition’] = “attachment; filename=\”#{filename}\""
render plain: pdf_content, content_type: ‘application/pdf’