简体   繁体   English

Django下载文件:UnicodeDecodeError

[英]Django downloading file:UnicodeDecodeError

I use Django 1.11 to download file.This is my function. 我使用Django 1.11下载文件。这是我的功能。

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 . 但是当我尝试下载.pdf文件时出现了UnicodeDecodeError 。实际上它仅在文件.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? 当我将包装器更改为open("file_name","rb") ,可以下载文件,但是无法打开文件。如何处理此问题?

Django's HttpResponse class is most suitable for a text based response (html page, txt file, etc.). Django的HttpResponse类最适合基于文本的响应(html页面,txt文件等)。 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. content转换为字符串时,可能会引发UnicodeDecodeError。 If you want to return a PDF file, the file content is binary data, so it is not intended to be converted to string. 如果要返回PDF文件,则文件内容为二进制数据,因此不打算将其转换为字符串。

You may use the FileResponse class instead. 您可以改用FileResponse类。 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). 它继承自StreamingHttpResponse,因此具有与HttpResponse不同的APi,但返回二进制文件(如PDF)可能会更好。

Try adding an encoding to the file that you are opening like this: 尝试将编码添加到要打开的文件中,如下所示:

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

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM