[英]'utf-8' codec can't decode byte 0x97 in position 14: invalid start byte
I want to download one directory from my server on button click. 单击按钮后,我想从服务器下载一个目录。 The directory should be downloaded in zip format.
该目录应以zip格式下载。 I am using Django and Python.
我正在使用Django和Python。 I tried this earlier with the same code but it was on Python2 venv.
我之前用相同的代码尝试了此操作,但它在Python2 venv上。 The same code on Python3 venv gives utf-8 codec can't decode byte error.
Python3 venv上的相同代码使utf-8编解码器无法解码字节错误。 The zip of the directory is created successfully but when i press the download button on my website it throws me above error.
该目录的zip文件已成功创建,但是当我按我网站上的下载按钮时,它使我抛出了错误。
@login_required
def logs_folder_index(request):
user = request.user
if not is_moderator(user):
raise Http404("You are not allowed to see this page.")
else:
if os.path.exists('Experiments.zip'):
os.remove('Experiments.zip')
zipf = zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED)
path = settings.BASE_DIR + '/experiments/'
zipdir(path,zipf)
zipf.close()
zip_file = open('Experiments.zip','r')
response = HttpResponse(zip_file,
content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="{0}"'\
.format(Experiments.zip)
return response
Can someone please help me with this problem. 有人可以帮我解决这个问题。
Your read the file as a text stream (since the mode is 'r'
, and not 'rb'
). 您将文件作为文本流读取(因为模式为
'r'
,而不是'rb'
)。 Since zips are typically not encoded in UTF-8 (or any text codec in general), it is likely to eventually reach a byte sequence that can not be decoded (or will be decoded non-sensical), you thus should read it as a binary file: 由于zip通常不会以UTF-8(或一般而言,任何文本编解码器)进行编码,因此最终可能会到达无法解码(或将被毫无意义地解码)的字节序列,因此您应将其读为二进制文件:
@login_required
def logs_folder_index(request):
user = request.user
if not is_moderator(user):
raise Http404("You are not allowed to see this page.")
elif os.path.exists('Experiments.zip'):
os.remove('Experiments.zip')
with zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED) as zipf:
path = settings.BASE_DIR + '/experiments/'
zipdir(path,zipf)
with open('Experiments.zip',
'rb') as stream:
response = HttpResponse(stream, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="Experiments.zip"'
return response
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.