Ali_Hr
Ali_Hr

Reputation: 4675

how to send multiple files with one key in laravel using guzzle Http

I can send multiple files and string data with post man like bellow:

enter image description here

but the question is how to send similar request with laravel http ?

what I did is :


public function performMultiPartRequest($requestUrl, $body)
    {
        $response = Http::withHeaders(['Accept' => 'application/json']);
        $data = [];
        foreach ($body as $key => $value) {
            if (gettype($value) == 'string') // for string data. works well.
                array_push($data,[$key, $value]);
            else if (gettype($value) == 'array') { // array of files. doesn't work!
                foreach ($value as $file) {
                    $extension = $file->getClientOriginalExtension();
                    $response->attach($key , fopen($file, 'r'), mt_rand(100,1000).".".$extension);
                }
            }
            else { // one file. works well.
                $extension = $value->getClientOriginalExtension();
                $response->attach($key, fopen($value, 'r'), 'temp.'.$extension);
            }
        }
        $response = $response->post($this->baseUri.$requestUrl, $body);
        return $response;

    }

when I try to send some string key value with a file or files with different keys, it's ok, but when I try to send data with multiple file upload (one key) error happens.

the error message is: A 'contents' key is required with status code 0

Upvotes: 2

Views: 2035

Answers (1)

Ali_Hr
Ali_Hr

Reputation: 4675

unfortunately I didn't find a solution to do the job with Illuminate\Support\Facades\Http yet, but because of time limitation of the project, I used GuzzleHttp\Client instead:


            $client = new Client([
                "base_uri" => $url,
            ]);
            $data = [];
            $data['multipart'] = [];
            foreach ($body as $key => $value) {
                if (gettype($value) == 'string') {
                    array_push($data['multipart'], [
                        'name' => $key,
                        'contents' => $value
                    ]);
                } else if (gettype($value) == 'array') {
                    foreach ($value as $k =>  $file) {
                        if (file_exists($file)) {
                            $extension = $file->getClientOriginalExtension();
                            array_push($data['multipart'], [
                                'name' => $key."[]",
                                'contents' => fopen($file, 'r'),
                                'filename' => mt_rand(100, 1000) . "." . $extension
                            ]);
                        }
                    }
                }
            }

            $response = $client->request('POST', $requestUrl, $data);

it works fine for my case. but any solution to laravel Http facade will be appreciated for this problem.

Upvotes: 2

Related Questions