1

I create a link that when a user press it, it will download a pdf file from the media folder in Django to the users machine.

I tried different methods but all were wrong for me. It tells me that the file can not be found, or the code is running but the file is corrupted.

My Html link:

<td>  <a href="/download/">Download</a></td>

My url pattern links into a view:

url(r'^download/$', views.DownloadPdf),

My FileField is like this:

upload_pdf = models.FileField()

Following snippet code is the view that downloads a corrupted pdf:

def DownloadPdf(request):

filename = '/home/USER/PycharmProjects/MyProject/media/Invoice_Template.pdf'
response = HttpResponse(content_type='application/pdf')
fileformat = "pdf"
response['Content-Disposition'] = 'attachment;
filename=thisismypdf'.format(fileformat)
return response

So, what I have to do to make it working ?

Amir
  • 8,821
  • 7
  • 44
  • 48
Vaios Lk
  • 51
  • 1
  • 10
  • You should serve your `media` folder with you webserver. In development the development server will do this task. Please read https://docs.djangoproject.com/en/1.10/howto/static-files/ for details. – Klaus D. Nov 10 '16 at 09:22

2 Answers2

1
with open(os.path.join(settings.MEDIA_ROOT, 'Invoice_Template.pdf'), 'rb') as fh:
    response = HttpResponse(fh.read(), content_type="application/pdf")
    response['Content-Disposition'] = 'attachment; filename=invoice.pdf'
    return response
Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39
1

@Sergey Gornostaev 's code just work perfect, but i post below my code because it is a aproach in a differect way.

I correct a little bit my code:

def DownloadPdf(request):
    path_to_file = '/home/USER/PycharmProjects/MyProject/media /Invoice_Template.pdf'
    f = open(path_to_file, 'r')
    myfile = File(f)
    response = HttpResponse(myfile, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=filename'
    return response

But only in pdf file ( works with txt files ) gives me that error:

'utf-8' codec can't decode byte 0xe2 in position 10

Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39
Vaios Lk
  • 51
  • 1
  • 10