From 57789dc5a52bbf08794fa4ab373802f0e2bdb5cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=83=A1=E5=B0=A7?= Date: Sun, 27 Apr 2025 15:10:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=8A=E4=BC=A0ftp?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sf_machine_connect/models/ftp_operate.py | 46 ++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/sf_machine_connect/models/ftp_operate.py b/sf_machine_connect/models/ftp_operate.py index 8265b351..89230170 100644 --- a/sf_machine_connect/models/ftp_operate.py +++ b/sf_machine_connect/models/ftp_operate.py @@ -261,8 +261,50 @@ def transfer_files( target_path = f"{target_dir}/{relative_path}/{item}" else: target_path = f"{target_dir}/{item}" - with open(temp_path, 'rb') as f: - target_ftp.ftp.storbinary(f'STOR {target_path}', f) + + # 规范化路径 + target_path = target_path.replace('\\', '/').strip('/') + + # 确保目标目录存在 + target_dir_path = '/'.join(target_path.split('/')[:-1]) + try: + target_ftp.ftp.cwd('/') # 回到根目录 + for dir_part in target_dir_path.split('/'): + if dir_part: + try: + target_ftp.ftp.cwd(dir_part) + except: + try: + target_ftp.ftp.mkd(dir_part) + target_ftp.ftp.cwd(dir_part) + except Exception as e: + logging.error(f"创建目录失败 {dir_part}: {str(e)}") + raise + except Exception as e: + logging.error(f"处理目标目录失败: {str(e)}") + raise + + # 检查FTP连接状态 + try: + target_ftp.ftp.voidcmd('NOOP') + except: + logging.error("FTP连接已断开,尝试重新连接") + target_ftp.ftp.connect(target_ftp_info['host'], target_ftp_info['port']) + target_ftp.ftp.login(target_ftp_info['username'], target_ftp_info['password']) + + # 上传文件 + try: + with open(temp_path, 'rb') as f: + # 检查文件是否可读 + content = f.read() + if not content: + raise Exception("临时文件为空") + f.seek(0) # 重置文件指针 + target_ftp.ftp.storbinary(f'STOR {target_path}', f) + except Exception as e: + logging.error(f"上传文件失败: {str(e)}") + logging.error(f"目标路径: {target_path}") + raise transfered_file_list.append(item) # 删除临时文件