You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将流式获取的file_stream传入MultipartEncoder实现流式上传?

如何将流式获取的文件传入MultipartEncoder?

问题描述

希望将文件流式上传至Web服务器,使用requests-toolbelt库的MultipartEncoder工具完成上传,但不想将文件保存到本地磁盘——目前通过requests.get(url, stream=True)获取了流式的Response对象(file_stream),需要直接将这个流传入MultipartEncoder完成上传。

解决方案

MultipartEncoder支持传入类文件对象(只要实现了read()方法),而requests的Response对象本身就是符合要求的类文件对象,因此可以直接将其传入MultipartEncoder的fields参数中,无需保存到磁盘。

完整代码示例

from requests_toolbelt import MultipartEncoder
import requests

def stream_and_upload():
    # 流式获取远程文件
    source_url = "https://webserver.com/file.zip"
    with requests.get(source_url, stream=True) as file_stream:
        file_stream.raise_for_status()  # 检查源文件请求是否成功
        
        # 初始化MultipartEncoder,直接传入流式Response对象
        multipart_data = MultipartEncoder(
            fields={
                'field0': 'form_value_0',
                'field1': 'form_value_1',
                # 格式:(文件名, 类文件对象, 文件MIME类型)
                'upload_file': ('file.zip', file_stream, 'application/zip')
            }
        )
        
        # 执行流式上传到目标服务器
        upload_target_url = "http://httpbin.org/post"
        with requests.post(
            upload_target_url,
            data=multipart_data,
            headers={'Content-Type': multipart_data.content_type}
        ) as upload_response:
            upload_response.raise_for_status()
            print(upload_response.json())

关键注意事项

  • 保持流的打开状态:必须将MultipartEncoder的创建和上传操作放在with requests.get(...) as file_stream的代码块内部,否则出块后file_stream会被自动关闭,无法读取内容。
  • 正确配置文件参数:和上传本地文件的格式一致,需要指定文件名、类文件对象(file_stream)以及对应的MIME类型(如application/zip)。
  • 错误处理:使用raise_for_status()可以在请求失败时主动抛出异常,避免静默失败。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:52:12