Serve pdf file as download using Pyramid, ningx, X-Accel-Redirect header

I want the user to be able to click a link like this:

<a href="/download?file=123">download</a>

Ask Pyramid 1.2.7 to process a view like this

 @view_config(route_name='download') def download(request): file_id = request.GET['file'] filename = get_filename(file_id) headers = request.response.headers headers['Content-Description'] = 'File Transfer' headers['Content-Type'] = 'application/force-download' headers['Accept-Ranges'] = 'bytes' headers['X-Accel-Redirect'] = ("/path/" + filename + ".pdf") return request.response 

And my nginx configuration looks like

 location /path/ { internal; root /opt/tmp; } 

This all works, but instead of the browser showing the pdf download, the browser displays a bunch of PDF garbage.

How to customize Pyramid view to get browser to do the right thing?

+4
source share
1 answer

If you want to indicate that the web browser should load the resource, and not display it, try using the Content-Disposition header as described in RFC 6266 . For example, the following response header tells the browser to download the file:

 Content-Disposition: attachment 

You can also specify the file name for the downloaded file through this header (if it differs from the last component of the path in the URL):

 Content-Disposition: attachment; filename=foo.pdf 

Looking at the Nginx documentation , this response header should work correctly in conjunction with the X-Accel-Redirect feature used.

+7
source

Source: https://habr.com/ru/post/1440696/


All Articles