0
votes

I am trying to uploading a video file to onedrive using the microsoft graph api with the php sdk implementation in laravel.

Code details as below

// Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = json_encode([ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ]);
    //dd(json_encode($postData));

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }

Not sure what should go into the item path too, i tried using the folder name but got error and i also tried excluding the item path but still got an error.

This is the error I am getting

Client error: `POST https://graph.microsoft.com/v1.0/drive/root/createUploadSession` resulted in a `400 Bad Request` response: {
 "error": {
 "code": "BadRequest",
 "message": "Unable to read JSON request payload. Please ensure Content-T (truncated...)

Json Encode of the request data is also as below and I cant figure out the problem...

{"items":
  {
    "@odata.type":"microsoft.graph.driveItemUploadableProperties",
    "@microsoft.graph.conflictBehavior":"rename",
    "name":"new_video.mp4"
 }
}
1
Set content type header to application/jsonElias Soares
@EliasSoares, yes I added that but still getting the same errorLance Armah-Abraham

1 Answers

0
votes

According to this example given on msgraph-sdk-php repository you don't need to json_econde your body data. The sdk will do it for you.

So your code should looks like this:

    // Get the access token from the cache
    $tokenCache = new TokenCache();
    $accessToken = $tokenCache->getAccessToken();

    $file_name = 'new_video.mp4';
    $media_path = storage_path('video.mp4');

    // Create a Graph client
    $graph = new Graph();
    $graph->setAccessToken($accessToken);

          //create post request
    $postData = [ 'items' =>
                    [
                        "@odata.type" => "microsoft.graph.driveItemUploadableProperties",
                        "@microsoft.graph.conflictBehavior" => "rename",
                        "name" => $file_name
                    ]
                ];

    try {
        $post = $graph->createRequest('POST', '/drive/root/:{item-path}:/createUploadSession')->attachBody($postData)->upload($media_path);

    } catch (\Illuminate\Http\Client\RequestException $e) {
        dd($e);
    }