在现代Django中,如何从一个文件夹中创建一个包含多个文件的zip文件,并将其发送到浏览器



我一直在努力将可下载的Django压缩包和许多文件发送到浏览器,因为网络上的许多教程都过时了,就像我的灵感来源一样,我将与你分享:

Django -创建多个文件的Zip并使其可下载

解决方案

我们在这个项目中没有使用很多函数,而是使用带有文档字符串的代码块,但是您可以轻松地将这些代码打包到一个函数中:

from io import BytesIO
from zipfile import ZipFile
from django.http import HttpResponse
#get the name of the folder you want to download from the frontend using input
directory_name = request.POST["folder"]
#create the zip file
file_blueprint = BytesIO()
zip_file = ZipFile(file_blueprint, 'a')
#create the full path to the folder you want to download the files from
directory_path = BASE_PATH + directory_name
for filename in os.listdir(directory_path):
try:
#characterize the from path and the destination path as first and second argument
zip_file.write(os.path.join(directory_path + "/" + filename), os.path.join(directory_name + "/" + filename))
except Exception as e:
print(e)
zip_file.close()
#define the the zip file as a response
response = HttpResponse(file_blueprint.getvalue(), content_type = "application/x-zip-compressed")
response["Content-Disposition"] = "attachment; filename= your-zip-folder-name.zip"
return response

相关内容

最新更新