K
K
KIN19912015-04-08 12:54:16
Django
KIN1991, 2015-04-08 12:54:16

How to give a media file in django?

Hello everyone, actually a question on a subject.
There are files of different formats, how can they be given for download from view (controller)?
You need something like
views.py

def get_file(request):
    file object = ....
    return file_object

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Shandrinov, 2015-04-08
@KIN1991

ktt

from django.core.servers.basehttp import FileWrapper

def get_file(request):
    filename = '...'
    content_type = 'application/vnd.ms-excel'
    file_path = os.path.join(store_path, filename)
    response = HttpResponse(FileWrapper(file(file_path)), content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % (
        filename.encode('utf-8') if isinstance(filename, unicode) else filename,
    )
    response['Content-Length'] = os.path.getsize(path)
    return response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question