Home > Software design >  Django Error: 'utf-8' codec can't decode byte when trying to create downloadable file
Django Error: 'utf-8' codec can't decode byte when trying to create downloadable file

Time:09-29

I have created an app, to do some process and zip some files. Now I need to make the zip file downloadable for users, so they can download the zip file.

I am working with Django and here is the in views.py:

def download(request):
    context = {}
if request.method == 'POST':
    if form.is_valid():
        userInput = form.cleaned_data['userInput']
        createFiles(userInput)

        filename = 'reports.zip'
        filepath = '/home/download/'

        fl = open(filepath, 'r')
        mime_type, _ = mimetypes.guess_type(filepath)

        response = HttpResponse(fl, content_type=mime_type)
        response['Content-Disposition'] = "attachment; filename=%s" % filename
        return response
return render(request, 'download.html', context)

But I am getting an error:

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

Which is breaking on this line:

response = HttpResponse(fl, content_type=mime_type)

Any suggestions how to fix this?

CodePudding user response:

I would guess, that you should open the zip file with 'rb' flags (binary).

Here's a sample from my working code:

zip_fullpath = os.path.join(zip_path, zip_filename)
zip_file = open(zip_fullpath, 'rb')
resp = FileResponse(
    zip_file,
    content_type="application/force-download"
)
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
os.remove(zip_fullpath)
return resp
  • Related