post发送文件

import requests

def post_file_with_form(url, file_path, file_field_name='file', additional_data=None):
    """
    发送包含文件的POST请求
    
    参数:
        url: 目标URL
        file_path: 要上传的文件路径
        file_field_name: 表单中文件字段的名称,默认为'file'
        additional_data: 其他表单数据,字典格式,默认为None
    """
    try:
        # 准备其他表单数据
        data = additional_data if additional_data else {}
        
        # 准备文件数据,格式为: {字段名: (文件名, 文件对象, MIME类型)}
        with open(file_path, 'rb') as file:
            files = {
                file_field_name: (file_path.split('/')[-1], file)
            }
            
            # 发送POST请求
            response = requests.post(url, data=data, files=files)
            
            # 检查响应状态
            response.raise_for_status()
            
            print(f"文件上传成功!状态码: {response.status_code}")
            return response.text
            
    except FileNotFoundError:
        print(f"错误: 文件 '{file_path}' 未找到")
    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")
    
    return None

# 使用示例
if __name__ == "__main__":
    # 目标URL(替换为实际的API端点)
    upload_url = "http://192.168.10.236:8111/api/v2/process/image"
    
    # 要上传的文件路径
    file_to_upload = "白字黑底.png"
    
    # 其他需要一起发送的表单数据
    form_data = {
        "username": "test_user",
        "description": "这是一个测试文件"
    }
    
    # 发送请求
    result = post_file_with_form(
        url=upload_url,
        file_path=file_to_upload,
        file_field_name='file',  # 服务器期望的文件字段名
        # additional_data=form_data
    )
    
    if result:
        print("服务器响应:")
        print(result)

posted on 2025-09-19 09:30  张博的博客  阅读(7)  评论(0)    收藏  举报

导航