问题
I need to take an image from storage in Laravel and send it from a Controller to an external API REST.
I am using guzzlehttp multipart but the API didn't receive the file, returns file = null
回答1:
This is how I did it a few days ago (taking file from Request):
For single file:
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);
}
For multiple files:
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);
}
来源:https://stackoverflow.com/questions/60169118/how-to-send-image-from-laravel-controller-to-api-rest