让用户下载文件+ Django [英] Letting user download a file + django

查看:132
本文介绍了让用户下载文件+ Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web应用程序使用户可以搜索目录中的文件,并返回指向与特定时间范围匹配的文件的链接。

My web app lets a user search through files in a directory and returns a link to files that match a certain time frame.

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

The user is able to click on any link and view the contents of a file via some URL.

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

I'd rather have the user be able to click a link and download the file to their system rather than displaying the file contents on a separate page.

这就是我所拥有的到目前为止...

Here's what I have so far...

download.html

download.html

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

我们从此视图查看文件...

we view the file from this view...

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

$ b $

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

我不确定如何解决沿着这条路或走哪条路

I'm not sure how to tackle this or which path to go down

任何指导都值得赞赏! :)

Any guidance is much appreciated! :)

这是我的代码更改:

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


推荐答案

您快到了,但是您需要设置 Content-disposition 标头值,例如:

You're almost there, but you need to set the Content-disposition header value, like this:

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

这篇关于让用户下载文件+ Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆