4

这是我的问题:我在服务器上有一些 pdf 文件,我的 Django Web 应用程序托管在另一台服务器上(与 pdf 文件不同)。在我的应用程序中,我知道另一台服务器上的 pdf 文件链接。我想通过我的应用程序下载该 pdf 文件,而无需在 Web 服务器应用程序上阅读它们。

我试着解释一下。如果我点击下载链接,我的浏览器会在他的内部 pdf 查看器中显示 pdf。我不想要这个,我想要点击一个按钮,用户将下载文件而不在内部浏览器上打开它。

我看这里:http ://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment 但这不是对我来说是一个好方法,因为它要求我在我的网络应用程序中读取文件,然后将其返回给用户。

可能吗??

4

2 回答 2

3

嗯,听起来像是不适合这项工作的工具。您不能真正“重定向”并修改响应标头,这意味着使用 django 仅设置Content-Disposition标头将需要您通过 django 流式传输文件,然后让 django 将其流式传输到客户端。

让一个更轻量级的 Web 服务器来处理它。如果您碰巧使用的是 nginx,这里有一个很棒的解决方案,它 99% 适合您的场景(1% 是设置 nginx 正在等待的标头的轨道)。

如果您只想设置标题并且文件不需要 django 处理,那么代理会更容易!

如果您不使用 nginx,我会将标题更改为有关代理文件和设置标头的 Web 服务器特定问题。

于 2011-03-23T23:05:50.090 回答
0

我最近遇到了类似的问题。我已经解决了将文件下载到我的服务器然后将其写入HttpResponse 以下是我的代码的问题:

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 
于 2017-04-12T14:29:41.950 回答