def zipDir(dirpath, outFullName):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 压缩文件保存路径+xxxx.zip
:return: 无
"""
zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
# 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
fpath = path.replace(dirpath, '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
@app.route('/uploads/<path:filename>')
def download_file(filename):
"""
返给前端文件
:param filename: 前端希望下载的路径
:return: 文件或压缩后的文件夹
"""
folder="/code/"
filepath = folder + filename # 构造本机绝对路径
input_path,input_name=os.path.split(filepath)
# 判断路径是否存在,文件直接返回,文件夹压缩返回
if os.path.isdir(filepath):
print("it's a directory")
outFullName = input_path +'/'+ input_name+'.zip'
if not os.path.exists(outFullName):
zipDir(filepath, outFullName)
return send_from_directory(input_path,
input_name+'.zip', as_attachment=True)
elif os.path.isfile(filepath):
print("it's a normal file")
return send_from_directory(input_path,
input_name, as_attachment=True)
else:
return jsonify(bool=False, msg='No such file, please check file path')
参考教程:
https://www.kite.com/python/docs/flask.send_from_directory
https://blog.csdn.net/xuezhangjun0121/article/details/112619852