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

Laravel 8使用Guzzle ^7.3发送multipart/form-data POST请求报错求助

Laravel 8 + Guzzle 7.3 发送multipart/form-data请求问题排查方案

首先给出两种场景下的正确写法,你可以对照自己的代码核对:

Guzzle原生写法示例

$client = new \GuzzleHttp\Client();
$response = $client->post('替换为你的目标接口地址', [
    'multipart' => [
        // 普通文本参数
        [
            'name'     => 'field_name',
            'contents' => 'field_value'
        ],
        // 文件参数
        [
            'name'     => 'upload_file',
            'contents' => fopen(public_path('test.jpg'), 'r'),
            'filename' => 'custom_file_name.jpg'
        ]
    ]
]);

Laravel Http Facade写法示例

use Illuminate\Support\Facades\Http;

$response = Http::attach(
    'upload_file', // 接口要求的文件字段名
    file_get_contents(public_path('test.jpg')), // 文件内容
    'custom_file_name.jpg' // 自定义传给接口的文件名
)->post('替换为你的目标接口地址', [
    'field_name1' => 'value1',
    'field_name2' => 'value2'
]);

常见错误排查点

  • 不要手动在请求头中添加Content-Type: multipart/form-data,Guzzle会自动生成带唯一boundary标识的请求头,手动添加的头缺少boundary参数,服务端无法正常解析请求字段
  • 检查multipart数组的每一个子项都必须包含name和contents两个必填字段,缺少任意一个都会导致请求格式异常
  • 传递文件时确认文件路径正确、程序有文件读取权限,contents字段可以传文件资源、文件内容字符串,不要直接传文件路径字符串
  • 核对所有字段的name值和目标接口要求的完全一致,包括大小写、数组标识(如果要传数组类型的字段,name需要加[]后缀,比如tags[])
  • 如果返回参数校验错误,打印完整的响应内容查看具体的字段错误提示:dd($response->json())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:48:00