首页 > 解决方案 > 将文件发布到 API

问题描述

我正在使用"guzzlehttp/guzzle": "6.3". 当我将图像发布到我的 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()
    ]);
}

标签: phplaravelguzzle

解决方案


您需要将您的添加form_paramsmultipart数组中:

// 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;

推荐阅读