Home > Net >  Error while sending PDF through Django link
Error while sending PDF through Django link

Time:12-23

Fairly New to Django Here. I tried sending a CSV successfully using this code but I'm getting the following error sending a pdf file I generated using PDFpages from matplotlib

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 10: invalid start byte

Here's the code

def download_file(request):
    # fill these variables with real values
    fl_path = 'file.pdf'
    filename = 'report.pdf' 

    fl = open(fl_path, 'r', encoding='utf-8')
    mime_type, _ = mimetypes.guess_type(fl_path)
    print(mime_type)
    response = HttpResponse(fl, content_type=mime_type)
    response['Content-Disposition'] = "attachment; filename=%s" % filename
    return response

Is there a way to know which is the correct encoding I need to send my file through?

CodePudding user response:

Use django's FileResponse instead of HttpResponse, FileResponse is more ideal for send file data.

return FileResponse(fl, filename=''.format(filename ), as_attachment=True,
                                content_type='application/pdf')
  • Related