开发者

redirect and force download

this is my pr开发者_JS百科oblem: I have some pdf files on a server, my Django web-application is hosted on another server (not the same of the pdf files). On my appplication i know the pdf files link on the other server. I want to download that pdf files through my application without read them on web server application.

I try to explane. If i click on download link, my browser shows the pdf into his internal pdf viewer. I don't want this, i want that on click on a button the user will download the file without open it on internal browser.

I looked here: http://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment but this is not a good way for me, cause it requires that I read the file inside my web-application and after return it to the user.

Is it possible??


Hmm, sounds like the wrong tool for the job. You can't really "redirect" and modify the response header, which means using django just to set the Content-Disposition header would require you to stream the file through django, then have django stream it to the client.

Let a lighter weight web server handle that. If you happen to be using nginx, here's an awesome solution that fits your scenario 99% (the 1% being it's rails setting the header that nginx is waiting for).

If all you want is to set the header and the file doesn't need django processing, it would be even easier to proxy!

If you are not using nginx, I would change the title to a web server specific question about proxying a file & setting headers.


I had a similar problem recently. I have solved it downloading the file to my server and then writing it to the HttpResponse Here is my code:

import requests
from wsgiref.util import FileWrapper
from django.http import Http404, HttpResponse

def startDownload():
    url, filename, ext = someFancyLogic()
    request = requests.get(url, stream=True)

    # Was the request OK?
    if request.status_code != requests.codes.ok:
        return HttpResponse(status=400)

    wrapper = FileWrapper(request.raw)
    content_type = request.headers['content-type']
    content_len = request.headers['content-length']

    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = content_len
    response['Content-Disposition'] 
        = "attachment; filename={0}.{1}".format(filename, ext)
    return response 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜