Serve up pdf as a download with Pyramid, ningx, X-Accel-Redirect Header

穿精又带淫゛_ 提交于 2019-12-10 15:13:43

问题


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

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

Have a Pyramid 1.2.7 app handle the 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 this

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

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

How do I setup my Pyramid view to get the browser to do the right thing?


回答1:


If you want to indicate that a web browser should download a resource rather than display it, try using the Content-Disposition header as described in RFC 6266. For example, the following response header will tell the browser to download the file:

Content-Disposition: attachment

You can also specify a file name for the downloaded file through this header (if it differs from the last path component 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 you're using.



来源:https://stackoverflow.com/questions/12967734/serve-up-pdf-as-a-download-with-pyramid-ningx-x-accel-redirect-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!