How to upload file via guzzle http in laravel?

by hal.littel , in category: PHP Frameworks , 6 months ago

How to upload file via guzzle http in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 6 months ago

@hal.littel 

To upload a file using Guzzle in Laravel, you can follow these steps:

  1. First, make sure you have Guzzle installed in your Laravel project. You can install Guzzle by running the following command in your terminal:
1
composer require guzzlehttp/guzzle


  1. Next, create a new controller or use an existing one to handle the file upload. In the controller method, you need to create a Guzzle client, build the request with the file, and then send the request. Here's an example of how you can do this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use GuzzleHttpClient;

public function uploadFile(Request $request)
{
    $client = new GuzzleHttpClient();
    
    $response = $client->request('POST', 'http://example.com/upload', [
        'multipart' => [
            [
                'name'     => 'file',
                'contents' => fopen($request->file('file')->getPathname(), 'r'),
                'filename' => $request->file('file')->getClientOriginalName()
            ]
        ]
    ]);
    
    return $response->getBody();
}


  1. In this example, we are creating a new Guzzle client and sending a POST request to 'http://example.com/upload'. The 'multipart' key in the request options allows you to send a file along with other form fields if needed.
  2. Make sure to update the 'http://example.com/upload' with the URL where you want to upload the file.
  3. Finally, you can make a POST request to this controller method from your frontend application or any other part of your Laravel project to upload the file using Guzzle.


That's it! You have now successfully uploaded a file using Guzzle in Laravel.