Search code examples
phprestfile-uploadupload

Convert base64 string to blob and upload it to REST API using PHP


I need to upload a file (actually, it's a base64 string that is retrieved from another REST API) to a REST API that will accept blob as file content. In javascript, what I need to do is convert that base64 string to blob data, and pass it to a FormData and post it to the API endpoint.

I just don't know how to do that with PHP, using GuzzleHttp Client.

I hope someone with PHP skill can show me how to do that in PHP. I searched on Google but didn't seem to find a solution for me so far.

Thank you so much.


Solution

  • Just a rough and simple idea... i added as much comments i could to make it understandable... Hope this works out for you!

    $base64String = 'your_base64_encoded_data_here'; // base64 string
    //decode the base64 string and write it to a temporary file:
    $decodedData = base64_decode($base64String);
    
    $tempFilePath = tempnam(sys_get_temp_dir(), 'upload');
    //replace sys_get_temp_dir() with your custom dir if you want to change
    
    file_put_contents($tempFilePath, $decodedData);
    
    //or use fwrite 
    //fwrite(fopen($tempFilePath,"w+"),$decodedData);
    

    Use Guzzle to create a request and upload the file:

    require 'vendor/autoload.php';
    
    use GuzzleHttp\Client;
    use GuzzleHttp\Psr7\Request;
    use GuzzleHttp\Psr7\MultipartStream;
    
    $apiUrl = 'https://your_api.com/upload'; // replace with your api endpoint
    
    $client = new Client();
    
    // prepare data for multipart/form-data
    $multipart = new MultipartStream([
        [
            'name'     => 'file', // form field name
            'contents' => fopen($tempFilePath, 'r'),
            'filename' => 'uploaded_file' // file name
        ]
    ]);
    
    // create a psr-7 request object
    $request = new Request('POST', $apiUrl, ['Content-Type' => 'multipart/form-data; boundary=' . $multipart->getBoundary()], $multipart);
    
    // send request
    $response = $client->send($request);
    
    // final response
    echo $response->getBody();
    
    // delete the temporary file
    unlink($tempFilePath);
    //Or move to a a folder and schedule a cronjob to clean up the folder