How to send image from Laravel controller to API Rest [closed]

﹥>﹥吖頭↗ 提交于 2021-02-10 06:59:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!