I am uploading files in my Django application, which are recorded on the hard drive, and at a later moment they are retrieved. This works well for most files. However, every once in a while there is a file -- generally a PDF file -- that can't be retrieved properly. This is the error that comes up:
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 194: ordinal not in range(128)
I have seen other questions about this encoding issue, which all relate to how to deal with this when encoding plain text, but I am dealing with binary files. Here is my code:
Relevant upload code:
with open(path, "wb+") as destination:
for chunk in attachment.chunks():
destination.write(chunk)
Code to retrieve the file:
with open(file_path, "rb") as f:
contents = f.read()
response = HttpResponse(contents, content_type="application")
response["Content-Disposition"] = "attachment; filename=\""+name + "\""
I understand there is an encoding issue, but where exactly should I fix this?