The Rock
The Rock

Reputation: 413

Upload multiple files from Client to Server via API using HTTP guzzle in laravel 8

I tested by postman to attach file with field fileupload[0](see screenshot below) that works fine, request is added and fileupload also uploaded to server.

But I want to call that upload file api by my laravel HTTP Client

I have tried below code

$result = Http::attach(
            'attachment', $request->fileupload
        )->asForm()->post('http://192.168.1.100/api/request/store', $form_param);

my control in form upload:

 <input type="file" name="fileupload[]" multiple>

postman screenshot

But it seem like API server does not get my request file from the client side.

So how to upload file(or multiple files) via client using laravel HTTP?

Upvotes: 0

Views: 5185

Answers (1)

bhucho
bhucho

Reputation: 3420

There are few things you need to change.

This is a line written in documentation of guzzle. As Http Client is the wrapper class of guzzle it applies on it as well.

multipart cannot be used with the form_params option. You will need to use one or the other. Use form_params for application/x-www-form-urlencoded requests, and multipart for multipart/form-data requests.

Also as you shown in your screenshot of postman above as well, that you are content-type of your data is form-data not application/x-www-form-urlencoded.

So you cannot use asForm(). It internally sets content type to application/x-www-form-urlencoded.

The attach() function internally adds asMultipart() so you don't need to add it.

Secondly, In order to pass multiple attachment you need to pass array as first argument to the attach() function. For that

    if($request->hasFile('fileupload')) {
        $names = [];
        foreach ($request->file('fileupload') as $file) {
            if(file_exists($file)){
                $name= $file->getClientOriginalName();
                $names[] = $name;
            }
        }
    }

Now pass this array $names to the attach method,

$result = Http::attach(
            $names, $request->file('fileupload')
        )->post('http://192.168.1.100/api/request/store', $form_param);

If you pass array as first argument internally this function is recursive and calls itself to upload all files.


Though it is not part of question but I recommend calling http requests in the given format below.

   try{
   $result = Http::attach(
            $names, $request->file('fileupload')
        )->post('http://192.168.1.100/api/request/store', $form_param);
   $result->throw(); 
} catch(\Illuminate\Http\Client\RequestException $e){
   \Log::info($e->getMessage());
   // handle your exception accordingly
}

As it is never a guarantee that the response will always be ok.

Upvotes: 1

Related Questions