Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Upload Files From Frontend Server To API Server | Micro Service Architecture


Upload File From Frontend Server {GuzzleHttp} To REST API Server In PHP {Laravel}


Share On     Share On WhatsApp     Share On LinkedIn


In this article I will show you how to upload file from Frontend ie your customer facing web app to REST API.


Sometimes you might work with Micro Service architecture where you will have an API Server, Frontend Server, Database Server, where every piece of code resides in different servers. Then the main advantage of using this is the flexibility of using different technologies.


Let me show you how to upload the file from frontend to api server.


We will cover the following topics


  1. Setting Up Frontend & Backend Laravel App
  2. Staring Frontend & Backend Servers
  3. Download GuzzleHttp On Frontend App
  4. Frontend Form Creation
  5. Handle Form Submission In Frontend Controller
  6. Handling Request Data In API

Prerequisites


You should have a working laravel application or install fresh one with the following command


Frontend Laravel App

composer create-project --prefer-dist laravel/laravel frontend


API Laravel APP

composer create-project --prefer-dist laravel/laravel backend

1) Staring Frontend & Backend Servers


Now we have downloaded Laravel app and have setup both frontend and backend. Lets start the server the servers individually with the following command


Frontend Project

php artisan serve --port=8080


Backend Project

php artisan serve --port=8081

Accessing Frontend & Backend


As we saw above the frontend project can be access from web with the following command

Frontend (From Browser)

http://127.0.0.1:8080


Backend is nothing but the REST API project which we will internally consume from frontend project. Lets run the internal server so that we can access it from frontend with the following URL


Backend (REST API)

http://127.0.0.1:8081


2) Download GuzzleHttp On Frontend App


To make cross web requests you can use CURL. Since we will already we have Guzzle which is around the same and with advanced features we will use it. Use the following command to download the Guzzle Http composer package on frontend.


composer require guzzlehttp/guzzle 

3) Frontend Form Creation


web.php

Route::get('/upload_files', 'TestingController@create');
Route::post('upload_files', 'TestingController@store');


Lets start form creation to upload the file. Make sure to observe enctype="multipart/form-data"


Upload Form

<form action="{{ url('upload_files') }}" method="post" enctype="multipart/form-data">
    @csrf
    <p><input type="file" name="uploaded_file" id="file"></p>
    <p><input type="submit" value="Upload File"></p>
</form>


This is your normal form. Which has file field to upload any type of file.


Following is my routes to display the form field and where to send after submitting the form.



4) Handle Form Submission In Frontend Controller


As we saw routes from web.php that our form will now point to TestingController to method store we can can access the form fields with the following code


We can access the file uploads with the following code in the controller


$file               = request('uploaded_file');
$file_path          = $file->getPathname();
$file_mime          = $file->getMimeType('image');
$file_uploaded_name = $file->getClientOriginalName();


To start using Guzzle we can access with the following


$client = new \GuzzleHttp\Client();

/** Since we are using POST request I will demo the same */
$client->request("POST", $url_path_to_send_request, form_fields_or_multipart_fields);


Let me show you the actual code how to access it. I have explained everything in the code itself with comments.


/** REST API path where we want to send the data */
$uploadFileUrl = 'http://127.0.0.1:8081/api/upload-file';

/** Start Guzzle Client */
$client = new \GuzzleHttp\Client();

try {
    /** Guzzle CURL POST request */
    $response = $client->request("POST", $uploadFileUrl, [
        /** Multipart form data is your actual file upload form */
        'multipart' => [
            [
                /** This is the actual fields name that you will use to access in API */
                'name'      => 'uploaded_file',
                'filename' => $file_uploaded_name,
                'Mime-Type'=> $file_mime,

                /** This is the main line, we are reading from 
                    file temporary uploaded location  */
                'contents' => fopen($file_path, 'r'),
            ],
            /** Other form fields here, as we can't send form_fields with multipart same time */
            [
                /** This is the form filed that we will use to acess in API */
                'name' => 'form-data',
                /** We need to use json_encode to send the encoded data */
                'contents' => json_encode(
                    [
                        'first_name' => 'Channaveer',
                        'last_name' => 'Hakari'
                    ]
                )
            ]
        ]
    ]);
} catch (Exception $e) {
    /** This is generic exception, 
        you can even handle ServerException & ClientException of guzzle
    */
}

/** Check the response status code */
$code   = $response->getStatusCode();

/** Get the response body return by API */
$response   = $response->getBody();

/** 2nd parameter is true because I want in array format */
$responseData = json_decode($response, true);

/** Most of the time it will be JSON data so better decode the JSON to Array as follows  */
echo '<pre>';
print_r($responseData);

5) Handling Request Data In API


API's api.php routes


Route::post('upload-file', 'UploadsController@uploadFile');


Now lets handle the data that we got from Frontend and upload to specific path and return some code


UploadsController

public function uploadFile(Request $request)
{
    /** Other code like validation and some other stuff here */

    /** Following is the code which you will use to handle the file upload */
    if ($request->hasFile('uploaded_file')) {
        /** Make sure you will properly validate your file before uploading here */

        /** Get the file data here */
        $file = $request->file('uploaded_file');

        /** Generate random unique_name for file */
        $fileName = time().md5(time()).'.'.$file->getClientOriginalExtension();
        $file->move(public_path().'/uploads/test', $fileName);
        
        /** Return data */
        return response()->json([
            'status'    => 'success',
            'message'   => 'Your success message'
            'data'      => [
                'uploadedFileName' => $newFileName
            ]
        ], 200);   
    }
}


Caution


Make sure to handle the following in the above code


  1. Post Data Validation
  2. File Validations Like MIME Type, File Size, If Any Error In Form Upload
  3. Save New File Name In Database
  4. Proper return Data

Conclusion


Hope you found it useful. Kindly share with your friends.







Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing