如何将GraphQL多文件上传的Curl请求转为Laravel HTTP客户端实现
Laravel Http 实现 GraphQL 文件上传(对应指定Curl请求)
直接上对应Laravel Http组件的实现代码,完全匹配你给出的Curl请求:
// 本地文件路径 $filePath = 'example.jpg'; $response = Http::attach( // 对应Curl里的-F 0=@example.jpg,字段名必须和map中的键一致 '0', file_get_contents($filePath), basename($filePath) )->post('https://mygraphql', [ // 对应Curl中的operations参数,转成PHP数组再JSON编码 'operations' => json_encode([ 'query' => 'mutation ($file: Upload!) { my_aws_bucket { uploadFile(file: $file) { Key, Location } } }', 'variables' => ['file' => null] ]), // 对应Curl中的map参数,映射文件字段到GraphQL变量 'map' => json_encode([ '0' => ['variables.file'] ]), ]); // 处理响应结果 if ($response->successful()) { $result = $response->json(); $uploadKey = $result['data']['my_aws_bucket']['uploadFile']['Key']; $uploadLocation = $result['data']['my_aws_bucket']['uploadFile']['Location']; // 后续逻辑... } else { $errors = $response->json('errors') ?? $response->body(); // 错误处理... }
关键对应关系说明
Http::attach('0', ...):完全对应Curl中的-F 0=@example.jpg,字段名0必须和map里的键保持一致,否则GraphQL服务无法识别文件映射关系operations参数:将Curl中的JSON字符串转为PHP数组后再编码,避免手动拼接JSON出现格式错误map参数:明确告诉GraphQL服务,表单字段0对应到mutation变量variables.file
处理上传请求中的文件
如果是处理用户通过Laravel表单上传的文件(UploadedFile实例),可以直接用文件实例的方法替代本地文件读取:
// 假设$file是从请求中获取的上传文件,比如$request->file('uploaded_file') $response = Http::attach( '0', $file->getContent(), $file->getClientOriginalName() )->post('https://mygraphql', [ 'operations' => json_encode([ 'query' => 'mutation ($file: Upload!) { my_aws_bucket { uploadFile(file: $file) { Key, Location } } }', 'variables' => ['file' => null] ]), 'map' => json_encode([ '0' => ['variables.file'] ]), ]);
内容的提问来源于stack exchange,提问作者wivku
相关产品推荐
相关产品推荐

