Samuel Dauzon
Samuel Dauzon

Reputation: 11324

Django define name of file to serve

I have wrote a code which let user to download a file. This is the code :

def download_file(request, ref):
    filepath = "/home/jedema/code_"+ref+".txt"
    filename = os.path.basename(filepath)
    final_filename = "code.txt"
    return serve(request, filename, os.path.dirname(filepath))

I want to define the file name that user will download. At the moment, the name of downloaded file is the URL after my domain name.

Do you know how to define the name of file downloaded by user ?

Upvotes: 0

Views: 63

Answers (1)

red_clover
red_clover

Reputation: 106

You need to set the Content-Dispositionheader in your response. First of all you shouldn't use the serve() view, to deliver the file, because it only works as long as DEBUG = True is set.

With a look at the Django Docs something like the following should do the trick

def download_file(request, ref):
    filepath = "/home/jedema/code_"+ref+".txt"
    filename = os.path.basename(filepath)
    final_filename = "code.txt"
    with open(filepath) as f:
        response = HttpResponse(f.read(), content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="%s"' % final_filename
    return response

I haven't tested it but it should be a hint into the right direction

Upvotes: 2

Related Questions