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

寵の児 提交于 2021-01-29 21:53:45

问题


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>

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?


回答1:


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.



来源:https://stackoverflow.com/questions/65304647/upload-multiple-files-from-client-to-server-via-api-using-http-guzzle-in-laravel

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