Microsoft Graph API – Upload file to one drive – Unable to read JSON request payload. Please ensure Content-T

  graph, microsoft-graph-api, onedrive, php

I am using the msgraph-sdk-php for uploading a file to a folder in One Drive. I have used composer on ubuntu to install the sdk.I am using PHP 7.4

I get the following error:

GuzzleHttpExceptionClientException 

  Client error: `PUT https://graph.microsoft.com/v1.0/me/drive/root/10-01- 
  2021/children/invoices_10-01-2021.xlsx/content` resulted in a `400 Bad Request` response:
{
  "error": {
    "code": "BadRequest",
    "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)

  at vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113
    109|         if ($summary !== null) {
    110|             $message .= ":n{$summary}n";
    111|         }
    112| 
  > 113|         return new $className($message, $request, $response, $previous, $handlerContext);
    114|     }
    115| 
    116|     /**
    117|      * Obfuscates URI if there is a username and a password present

      +12 vendor frames 
  13  app/Console/Commands/OneDriveSync.php:99
      MicrosoftGraphHttpGraphRequest::upload()

      +13 vendor frames 
  27  artisan:37
      IlluminateFoundationConsoleKernel::handle()


My code is as follows :

$files = glob('/home/ubuntu/*'.$now.'*');
foreach ($files as $fileName)
     {
             error_log($fileName);
             $filePart  = explode("/",$fileName);
             error_log($filePart[count($filePart) - 1]);


        $graph = new Graph();
        $graph->setAccessToken($accessToken);

        $response  =  $graph->createRequest("PUT", "/me/drive/root/"."2021-01-01". ."/children/".$filePart[count($filePart) - 1]."/content")
              ->upload($fileName);

              error_log($response->getStatus());
              error_log($response->getRawBody());
              if($response->getStatus() != 201)
              {
                   return;
              }

        unlink($fileName);
     }

I checked the SDK documentation and the file upload example is similar to what I have done.
I am able to create a new folder on one drive using POST command of the same SDK.
The file is existing on the path and is readable.I have checked that.

Kindly help.

Source: Ask PHP

LEAVE A COMMENT