如何将图像从 Laravel 控制器发送到 API Rest
How to send image from Laravel controller to API Rest
我需要从 Laravel 中的存储中获取图像并将其从控制器发送到外部 API REST。
我正在使用 guzzlehttp multipart 但 API 没有收到文件,returns file = null
几天前我就是这样做的(从请求中获取文件):
对于单个文件:
public function storeProductImage(Request $request, $id){
$image = $request->file('image');
$body = [
"headers" => [
"Accept" => "multipart/form-data"
],
"multipart" => [
"name" => "image",
"contents" => file_get_contents($image),
"filename" => $image->getClientOriginalName()
]
];
return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
}
对于多个文件:
public function storeProductImage(Request $request, $id){
$body = [ "headers" => [
"Accept" => "multipart/form-data"
],
"multipart" => []
];
$images = $request->file('image');
if (is_array($images)) {
foreach ($images as $image) {
array_push($body["multipart"], ["name" => "image[]",
"contents" => file_get_contents($image),
"filename" => $image->getClientOriginalName()]);
}
}
return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
}
我需要从 Laravel 中的存储中获取图像并将其从控制器发送到外部 API REST。
我正在使用 guzzlehttp multipart 但 API 没有收到文件,returns file = null
几天前我就是这样做的(从请求中获取文件):
对于单个文件:
public function storeProductImage(Request $request, $id){
$image = $request->file('image');
$body = [
"headers" => [
"Accept" => "multipart/form-data"
],
"multipart" => [
"name" => "image",
"contents" => file_get_contents($image),
"filename" => $image->getClientOriginalName()
]
];
return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
}
对于多个文件:
public function storeProductImage(Request $request, $id){
$body = [ "headers" => [
"Accept" => "multipart/form-data"
],
"multipart" => []
];
$images = $request->file('image');
if (is_array($images)) {
foreach ($images as $image) {
array_push($body["multipart"], ["name" => "image[]",
"contents" => file_get_contents($image),
"filename" => $image->getClientOriginalName()]);
}
}
return \GuzzleHttp\Client::request('POST', 'product/'.$id.'/images', $body);
}