murderX
murderX

Reputation: 631

Django downloading file:UnicodeDecodeError

I use Django 1.11 to download file.This is my function.

def file_downloading(request, filename):
    path = settings.MEDIA_ROOT+'/'
    the_file_name = path+filename
    f_name = filename.split('/')[len(filename.split('/'))-1]
    wrapper = FileWrapper(open(the_file_name, "r"))
    content_type = mimetypes.guess_type(the_file_name)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(path) 
    response['Content-Disposition'] = 'attachment; filename=%s f_name 
    return response`

But I got a UnicodeDecodeError when I was trying to download .pdf file.Actually it only works when the file is .txt . When I change the wrapper to open("file_name","rb"),the file can be downloaded, but it can't be opened.How can I deal with this problem?

Upvotes: 0

Views: 1217

Answers (2)

Antwane
Antwane

Reputation: 22698

Django's HttpResponse class is most suitable for a text based response (html page, txt file, etc.). The documentation for the class constructor explains:

content should be an iterator or a string. If it’s an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed.

You UnicodeDecodeError is probably raised when the content is converted to a string. If you want to return a PDF file, the file content is binary data, so it is not intended to be converted to string.

You may use the FileResponse class instead. It inherits from StreamingHttpResponse, and so have a different APi than HttpResponse, but it will probably works better to return a binary file (like a PDF).

Upvotes: 2

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13763

Try adding an encoding to the file that you are opening like this:

open(the_file_name, 'r', encoding='utf-8')

Hope it helps.

Upvotes: 0

Related Questions