Symfony4下使用Guzzle7调用Akeneo Pim5上传图片报contents key required错误
问题原因
你遇到的A 'contents' key is required报错是Guzzle 7对multipart表单的参数格式要求不匹配导致的,同时还有几处请求配置不符合Akeneo接口规则,具体问题如下:
- Guzzle的
multipart参数要求传入索引数组,每一个表单项必须是包含name(表单字段名)和contents(字段值)的关联数组,你当前直接写关联数组的格式不符合要求 product字段需要传入序列化后的JSON字符串,不能直接传PHP数组- 手动设置
Content-Type: multipart/form-data属于多余配置,Guzzle会自动生成包含边界符(boundary)的该请求头,手动设置会丢失boundary导致服务端无法解析表单 Accept头配置错误,Akeneo接口返回格式为JSON,不需要设置为application/x-www-form-urlencoded
修复后的代码
$client2 = new Client(); $file = '/tmp/T_square.jpg'; // 先判断文件是否存在可读,避免资源无效报错 if (!is_readable($file)) { throw new \Exception('文件不存在或无读取权限'); } $url2 = "http://akeneo-pim.local/api/rest/v1/media-files"; $response2 = $client2->request('POST', $url2, [ 'headers' => [ 'Authorization' => 'Bearer ' . $response->access_token, 'Accept' => 'application/json' ], 'multipart' => [ // product表单项 [ 'name' => 'product', 'contents' => json_encode([ "identifier" => "teste_image", "attribute" => "picture", "locale" => null, "scope" => null ]) ], // 文件表单项 [ 'name' => 'file', 'contents' => fopen($file, 'r'), // 可选配置:指定上传文件名,不填则自动取源文件名称 'filename' => basename($file) ] ] ]);
排查建议
如果修改后仍有报错,可输出响应内容快速定位问题:
echo $response2->getBody();
内容的提问来源于stack exchange,提问作者Allen Prado
相关产品推荐
相关产品推荐

