让用户下载文件+ django(Letting user download a file + django)

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

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

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

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

download.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

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

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

<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

using this url..

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! :)

here are my code changes:

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头值,如下所示:

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

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

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

更多推荐