将文件发布到API

时间:2019-05-08 11:48:31

标签: php laravel guzzle

我正在使用"guzzlehttp/guzzle": "6.3"将图像发布到我的API中。当我将图像发布到API时,使用false检查文件时得到hasFile().,是否可能是文件未提交给我的API?

控制器

$client = new Client();
$url = 'http://localhost:9000/api';
$path = 'app/public/images/';
$name = '94.jpeg';
$myBody['fileinfo'] = ['449232323023'];
$myBody['image'] = file_get_contents($path.$name);
$request = $client->post($url, ['form_params' => $myBody]);
$response = $request->getBody();

return $response;

API

if (!$request->hasFile('image')) {
    return response()->json([
        'message' => 'No file',
        'photo' => $request->hasFile('image'),
        'photo_size' => $request->file('image')->getSize()
    ]);
}

1 个答案:

答案 0 :(得分:0)

您需要将form_params添加到multipart数组中:

// untested code

$client = new Client();

$endpoint = 'http://localhost:9000/api';
$filename = '94.jpeg';
$image = public_path('images/' . $filename);

$request = $client->post($endpoint, [
    'multipart' => [
        [
            'name' => 'fileinfo',
            'contents' => '449232323023',
        ],
        [
            'name' => 'file',
            'contents' => fopen($image, 'r'),
        ],
    ],
]);

$response = $request->getBody();

return $response;