Letting user download a file + django

2019-05-11 00:18发布

问题:

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

回答1:

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

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