单击按钮后,我想从服务器下载一个目录。该目录应以zip格式下载。我正在使用Django和Python。我之前用相同的代码尝试了此操作,但它在Python2 venv上。 Python3 venv上的相同代码给出了 utf-8编解码器无法解码字节错误。该目录的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
有人可以帮助我解决这个问题。
答案 0 :(得分:2)
您以文本流的方式读取文件(因为模式为'r'
,而不是'rb'
)。由于zip通常不会以UTF-8(或一般而言,任何文本编解码器)进行编码,因此最终可能会到达无法解码(或将被毫无意义地解码)的字节序列,因此您应将其读为 binary 文件:
@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