Reputation: 129
I am trying to make POST to a rest API where I need to send multiple files from a user input form. I have managed to get it to work with a single file, but when there are multiple files sent as an array ($file[]
), I can't see anything in the laravel docs to show how this can be done.
$response = 'API_URL';
$response = Http::withToken(ENV('API_KEY'))
->attach('file', fopen($request->file, 'r'))
->post($url, [
'uuid' => $request->uuid,
]);
Upvotes: 5
Views: 8472
Reputation: 8098
You can do it by:
->attach('file[0]', fopen($request->file[0], 'r'))
->attach('file[1]', fopen($request->file[1], 'r'))
if your $files
is an array of files that wants to send, you can do like below:
$response = Http::withToken(ENV('API_KEY'));
foreach ($files as $k => $file) {
$response = $response->attach('file['.$k.']', $file);
}
$response = $response->post($url, [
'uuid' => $request->uuid,
]);
Upvotes: 8
Reputation: 21
Attach multiple files if the file name also unknown, together with request data in one request, if request has file or does not have file. with authorization header
if ($method == 'POST') {
// Attached multiple file with the request data
$response = Http::withHeaders($headers);
if($request->files) {
foreach ($request->files as $key=> $file) {
if ($request->hasFile($key)) {
// get Illuminate\Http\UploadedFile instance
$image = $request->file($key);
$fileName = $request->file($key)->getClientOriginalName();
$response = $response->attach($key, $image->get(),$fileName);
}
}
$response = $response->post($this->$requestUrl, $request->all());
} else {
$response = Http::withHeaders($headers)->post($this->webApiBaseUri, $request->all());
}
}
Upvotes: 1