我的网络应用程序允许用户搜索目录中的文件,并返回与特定时间范围匹配的文件的链接。
用户可以单击任何链接并通过某个 URL 查看文件的内容。
我希望用户能够单击链接并将文件下载到他们的系统,而不是在单独的页面上显示文件内容。
这是我到目前为止所拥有的......
下载.html
<ul>
{% for file in match %}
<a href =/media/{{ file }}>{{ file }}</a>
<br></br>
{% endfor %}
</ul>
我们从此 View 查看文件...
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
最佳答案
您已经快完成了,但您需要设置 Content-disposition
header 值,如下所示:
response['Content-Disposition'] = "attachment; filename='fname.ext'"
关于django - 让用户下载文件+ django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32704177/