2017-05-29 85 views
0

我使用Django 1.11来下载文件。这是我的功能。Django下载文件:UnicodeDecodeError

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` 

但我得到了UnicodeDecodeError当我试图下载的.pdf file.Actually它,只有当该文件是.TXT工作。当我将包装器更改为open("file_name","rb")时,该文件可以下载,但无法打开。我该如何处理这个问题?

+0

the_file_name,“w”,试试这个 – Exprator

+0

尝试'wrapper = open(the_file_name,“rb”)',表示删除FileWrapper – itzMEonTV

+0

使用'os.path.join'来构造文件系统路径而不是字符串好得多concatentation。这样的代码更便携,更易于阅读。 –

回答

0

Django的HttpResponse类最适合基于文本的响应(html页面,txt文件等)。 documentation for the class constructor解释:

内容应该是迭代器或字符串。如果它是一个迭代器,它应该返回字符串,并且这些字符串将被连接在一起以形成响应的内容。如果它不是迭代器或字符串,它将在访问时转换为字符串。

UnicodeDecodeError可能在content转换为字符串时引发。如果你想返回一个PDF文件,文件内容是二进制数据,所以它不打算转换为字符串。

您可以改为使用FileResponse类。它继承自StreamingHttpResponse,因此具有与HttpResponse不同的APi,但它可能会更好地返回二进制文件(如PDF)。

+0

我使用'FileResponse'并在浏览器中返回错误代码...请给出关于它的具体示例吗? – murderX

0

尝试增加的编码要打开这样的文件:

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

希望它能帮助。

+0

'utf-8'编解码器无法解码位置11中的字节0x8f:无效的起始字节我忘了提供这些信息......我试过这种方式......但无论如何感谢您的帮助。 – murderX