【问题标题】:Letting user download a file + django让用户下载文件+ django
【发布时间】:2015-09-21 20:39:22
【问题描述】:

我的网络应用程序允许用户搜索目录中的文件并返回与特定时间范围匹配的文件的链接。

用户可以点击任何链接并通过某个 URL 查看文件的内容。

我希望用户能够单击链接并将文件下载到他们的系统,而不是在单独的页面上显示文件内容。

这是我目前所拥有的......

下载.html

<ul>
{% for file in match %}
    <a href =/media/{{ file }}>{{ file }}</a>
    <br></br>
{% endfor %}
</ul> 

我们从这个视图查看文件...

def xsendfile(request, path):  
    response = HttpResponse()
    response['Content-Type']=''
    response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path))
    return response

使用这个网址..

url(r'^media\/(?P<path>.*)$', views.xsendfile),

我不知道如何解决这个问题或走哪条路

非常感谢任何指导! :)

这是我的代码更改:

def xsendfile(request, path):  
    response = HttpResponse()
    response['Content-Type']=''
    response['Content-Disposition'] = "attachment; filename="+path
    response['X-Sendfile']= smart_str(os.path.join(settings.MEDIA_ROOT, path))
    return response

【问题讨论】:

    标签: django file download


    【解决方案1】:

    你快到了,但你需要设置 Content-disposition 标头值,如下所示:

    response['Content-Disposition'] = "attachment; filename='fname.ext'"
    

    【讨论】:

    • 你能检查一下我的实现吗
    • 如果您的代码更改后您的实现无法正常工作,可能您的服务器没有使用mod_xsendfile,这是执行此操作所必需的。如果你想抽象文件发送机制而不是绑定到服务器配置,你可以查找这个 django 库:github.com/johnsensible/django-sendfile
    【解决方案2】:

    先根据“路径”打开文件:

    with open(path, 'rb') as a: response = HttpResponse(a.read())

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 2012-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      相关资源
      最近更新 更多