压缩本地文件并上传到阿里云OSS
文章信息
创建日期:2025年1月14日
功能很简单,就是按照文件名中包含的内容来筛选出文件,并移动到设置的文件夹中。
代码如下:
import os
import zipfile
import oss2
# 配置阿里云OSS
OSS_ACCESS_KEY_ID = '****************' # 替换为你的AccessKeyId
OSS_ACCESS_KEY_SECRET = '****************' # 替换为你的AccessKeySecret
OSS_ENDPOINT = '***********************' # 替换为你的OSS地域节点,例如华东1为https://oss-cn-hangzhou.aliyuncs.com
OSS_BUCKET_NAME = '*******' # 替换为你的存储桶名称
OSS_OBJECT_NAME = '********' # 上传到OSS后的文件名
# 定义路径
build_folder = r'D:\工具\node-v22.12.0-win-x64\ifdess.cn\build'
zip_file_path = r'D:\工具\node-v22.12.0-win-x64\ifdess.cn\build.zip'
# 压缩文件夹为ZIP文件
def create_zip_from_folder(folder_path, zip_path):
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
# 计算相对路径,使文件结构保持一致
arcname = os.path.relpath(file_path, start=folder_path)
zipf.write(file_path, arcname)
print(f"压缩完成:{zip_path}")
# 上传文件到OSS
def upload_to_oss(file_path, bucket_name, object_name):
auth = oss2.Auth(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET)
bucket = oss2.Bucket(auth, OSS_ENDPOINT, bucket_name)
with open(file_path, 'rb') as f:
bucket.put_object(object_name, f)
print(f"文件已上传到OSS:{object_name}")
# 主程序
if __name__ == '__main__':
# 1. 创建压缩包
create_zip_from_folder(build_folder, zip_file_path)
# 2. 上传到OSS
upload_to_oss(zip_file_path, OSS_BUCKET_NAME, OSS_OBJECT_NAME)