5

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,
        ]);

2 Answers 2

8

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,
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks just what I was looking for
1

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());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.