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

使用boto分片上传大文件遇400错误:如何设置Content-Type?

解决Boto分片上传时的"Request Content-Type is not multipart/form-data"错误

这个400 Bad Request错误原因很明确——S3要求初始化分片上传的请求必须携带multipart/form-data类型的Content-Type头,而你的代码里没有显式设置这个参数,导致boto使用了默认的错误请求头类型。

修复方法

你只需要在调用initiate_multipart_upload方法时,通过headers参数传入正确的Content-Type即可:

修改原初始化上传的代码段:

# 原代码
mp = b.initiate_multipart_upload(os.path.basename(source_path))

# 修改后代码
headers = {'Content-Type': 'multipart/form-data'}
mp = b.initiate_multipart_upload(os.path.basename(source_path), headers=headers)

额外注意事项

  • 请确认你的source_path是指向具体文件而非目录:代码中os.stat(source_path).st_size是获取文件大小,如果路径指向目录会抛出异常,这也是潜在的问题点。
  • 如果需要添加其他自定义请求头或者元数据,可以直接把键值对加到headers字典里一起传入。

完整修改后的代码

import math, os
import boto.s3.connection
import boto
from filechunkio import FileChunkIO

# Connect to S3
c = boto.connect_s3()
b = c.get_bucket('bucketA')

# Get file info
source_path = './A/tmp1/your_target_file'  # 确保这里是具体文件路径
source_size = os.stat(source_path).st_size

# Create a multipart upload request with correct Content-Type
headers = {'Content-Type': 'multipart/form-data'}
mp = b.initiate_multipart_upload(os.path.basename(source_path), headers=headers)

# Use a chunk size of 50 MiB (feel free to change this)
chunk_size = 52428800
chunk_count = int(math.ceil(source_size / float(chunk_size)))

# Send the file parts, using FileChunkIO to create a file-like object
# that points to a certain byte range within the original file. We
# set bytes to never exceed the original file size.
for i in range(chunk_count):
    offset = chunk_size * i
    bytes = min(chunk_size, source_size - offset)
    with FileChunkIO(source_path, 'r', offset=offset, bytes=bytes) as fp:
        mp.upload_part_from_file(fp, part_num=i + 1)

# Finish the upload
mp.complete_upload()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:52:40