Laravel : I received song file “form-data” from one of API then i need to forward that file to another API. Any idea to forward?

故事扮演 提交于 2021-01-29 13:50:54

问题


Laravel project 1 controller how to forward file to API-2

Input::file('songFile')->move("/tmp", $newname);

i used this function and store tmp location then how to use this tmp location file and forward?


回答1:


In order to post a file to API endpoint, you can follow the following code.

try{
$path = 'var/www/html/myproject/public/file.txt';//your file path
if (!empty($path) && file_exists($path)) {

   $guzzleResponse = $client->post($api_url, [
       'multipart' => [
                        [
                            'name' => 'file',// it is the name as specfied in the payload of api_url
                            'contents' => fopen($path, 'r')// or you can use file_get_contents()
                        ]
                    ],
                    'headers' => $headers
       ]);
}
if ($guzzleResponse->getStatusCode() == 200) {
   $response = json_decode($guzzleResponse->getBody());// whatever you want to do with response
}
}catch(RequestException $e){
    return $e;  //You can also handle specific status codes here using eg $e->getResponse()->getStatusCode() == '400'
}

Also $headers can be like this

[
     'Accept'                => 'application/json',
     'Authorization'         => 'Bearer '. $userToken,
]

See more information in Guzzle



来源:https://stackoverflow.com/questions/63559380/laravel-i-received-song-file-form-data-from-one-of-api-then-i-need-to-forwar

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