2

in my Django 'views, I create a pdf file and I want to download it. The file exist (path: /app/data/4.pdf) and i launch this command:

def download_line(request):
    if not request.is_ajax() and not request.method == 'GET':
        raise Http404

    try:
        fs =FileSystemStorage('/app/data')
        with fs.open('4.pdf') as pdf:
            response =HttpResponse(pdf,content_type='application/pdf')
            response['Content-Disposition']='attachment; filename="4.pdf"'


    except Exception as e:
        logger.warning("Download Line | Erreur : " + e.message)


    return response

But the download doesn't start and no error. Have you got a solution? Thanks.

Kallz
  • 3,244
  • 1
  • 20
  • 38
smiss
  • 63
  • 1
  • 8

4 Answers4

2

I use FileResponse to serve file download, when the file already exists. FileResponse has been around since Django 1.7.4.

from django.core.files.storage import FileSystemStorage
from django.http import FileResponse

def download_line(request):
    fs = FileSystemStorage('/absolute/folder/name')
    FileResponse(fs.open('filename.pdf', 'rb'), content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename="filename.pdf"'
    return response
Husni
  • 121
  • 1
  • 4
2

You can download existing file in your app by a link and static, like this

<a href="{% static 'questions/import_files/import_questions.xlsx' %}" download>Excel Format File </a>
double-beep
  • 5,031
  • 17
  • 33
  • 41
-1

Try this, I use this lines to download files

from django.http import HttpResponse
from wsgiref.util import FileWrapper

import os

def download(request, file_path):
    """
    e.g.: file_path = '/tmp/file.pdf'
    """
    try:
        wrapper = FileWrapper(open(file_path, 'rb'))
        response = HttpResponse(wrapper, content_type='application/force-download')
        response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
        return response
    except Exception as e:
        return None
Jacek B Budzynski
  • 1,393
  • 1
  • 7
  • 13
-2
def sample_download_client_excel(request):
    """
    e.g.: file_path = '/tmp/file.pdf'
    """
    try:
        obj = SampleFile.objects.all().first()
        file_path = obj.file_name.url.strip('/') 
        wrapper = FileWrapper(open(file_path, 'rb'))
        response = HttpResponse(
            wrapper, 
            content_type='application/force-download'
        )
        response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
        return response
    except Exception as e:
        return None
Cartucho
  • 3,257
  • 2
  • 30
  • 55