import oss2 from pathlib import Path class AliyunOSSUploader: def __init__(self): self.access_key_id = "LTAI5tGTySgnmBWAzQMtKDSS" self.secret_access_key = "V3c7TI4KfK9ks8ReZGhSbADjX6avT0" self.endpoint = "oss-cn-beijing.aliyuncs.com" self.bucket_name = "remote-xtl" auth = oss2.Auth(self.access_key_id, self.secret_access_key) self.bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name) def _progress_callback(self, consumed_bytes, total_bytes): if total_bytes: rate = int(consumed_bytes * 100 / total_bytes) print(f"\r上传进度: {rate}% ({consumed_bytes}/{total_bytes} bytes)", end="") def upload(self, file_path, oss_object_name=None): file_path = Path(file_path) if not file_path.exists(): raise FileNotFoundError(f"文件不存在: {file_path}") if oss_object_name is None: oss_object_name = file_path.name print(f"正在上传: {file_path}") print(f"目标: oss://{self.bucket_name}/{oss_object_name}") self.bucket.put_object_from_file( oss_object_name, str(file_path), progress_callback=self._progress_callback ) print(f"\n上传成功!") url = f"https://{self.bucket_name}.{self.endpoint}/{oss_object_name}" print(f"访问地址: {url}") return url if __name__ == "__main__": uploader = AliyunOSSUploader() print("=" * 50) print("阿里云 OSS 文件上传工具") print("=" * 50) file_path = input("\n请输入文件绝对路径: ").strip().strip('"').strip("'") try: uploader.upload(file_path) except FileNotFoundError as e: print(f"\n错误: {e}") except Exception as e: print(f"\n上传失败: {e}")