django实现zip格式压缩文件或文件夹
view视图代码:
import os
import zipfile
from django.http import HttpResponse
def zip_ya(startdir):
startdir = r"C:\Users\17513\Desktop\aaa" # 要压缩的文件夹路径
file_news = startdir +'.zip'
z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(startdir):
fpath = dirpath.replace(startdir, '')
fpath = fpath and fpath + os.sep or ''
for filename in filenames:
z.write(os.path.join(dirpath, filename), fpath + filename)
z.close()
return HttpResponse('ok')
startdir = r"C:\Users\17513\Desktop\aaa"
urls代码:
path('zip/', views.zip_ya),
实现效果: