Microsoft Graph API file upload using PHP SDK for large file still fails

microsoft graph api upload file to onedrive
onedrive api upload file
upload file to onedrive using php
microsoft graph api php library
microsoft graph api upload large file
php graph sdk
microsoft graph api upload file c#
github microsoft graph

I am currently using microsoft-php-sdk and it has been pretty good. I have managed to upload small files from the server to OneDrive. But when I tried to upload a 38MB Powerpoint file it was failing. The Microsoft Graph API documentation suggests creating an upload session. I thought it would just be as easy as just updating the URI from /content to /createUploadSession but it was still failing.

$response = $graph->createRequest('POST', '/me/drive/root/children/'.basename($path).'/createUploadSession')
      ->setReturnType(Model\DriveItem::class)
      ->upload($path);

My code looks something like this. I have difficulty figuring out the PHP SDK documentation and there was no example for upload session. Has anyone used the PHP SDK for this scenario before?


I'm not familiar with PHP, but I am familiar with the upload API. Hopefully this will help.

The /content endpoint you were using before allows you to write binary contents to a file directly and returns a DriveItem as your code expects. The /createUploadSession method works differently. The Graph documentation for resumable upload details this, but I'll summarize here.

  1. Instead of sending the binary contents in the CreateUploadSession request, you either send an empty body or you send a JSON payload with metadata like the filename or conflict-resolution behavior.
  2. The response from CreateUploadSession is an UploadSession object, not a DriveItem. The object has an uploadUrl property that you use to send the binary data.
  3. Upload your binary data over multiple requests using the HTTP Content-Range header to indicate which byte range you're uploading.
  4. Once the server receives the last bytes of the file, the upload automatically finishes.

While this overview illustrates the basics, there are some more concepts you should code around. For example, if one of your byte ranges fails to upload, you need to ask the server which byte ranges it already has and where to resume. That and other things are detailed in the docs. https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/driveitem_createuploadsession

Resumable file upload, Upload large files with an upload session An upload session allows your app to upload ranges of the file in sequential API requests, which allows the Uploading fragments out of order will result in an error. If this occurs, your app can still resume the file transfer from the previously completed fragment. Namespace: microsoft.graph. The simple upload API allows you to provide the contents of a new file or update the contents of an existing file in a single API call. This method only supports files up to 4MB in size. To upload large files see Upload large files with an upload session. Permissions


I have developed a similar library for oneDrive based on microsoft graph rest api. This problem is also solved here : tarask/oneDrive

look at the documentation in the Upload large files section

Microsoft Graph API file upload using PHP SDK for large file still fails, I am currently using microsoft-php-sdk and it has been pretty good. I have managed to upload small files from the server to OneDrive. But when  I was able to upload a 1.5GB file. Great! Now, the problem is, I couldn't find any way to upload files to a shared folder. I couldn't find any suitable method in the API documentation. Neither PUT nor using an Upload Session. So, I don't think this is a limitation of the SDK, but in the API itself. I find this very weird.


i used the similar approach with https://github.com/microsoftgraph/msgraph-sdk-php/wiki and laravel framework. here is the code that worked for me finally.

public function test()
{
    //initialization
    $viewData = $this->loadViewData();

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

// Create a Graph client
$graph = new Graph();
$graph->setAccessToken($accessToken);
//upload larger files
// 1. create upload session
        $fileLocation = 'S:\ebooks\myLargeEbook.pdf';


         $file =  \File::get($fileLocation);
            $reqBody=array(
    "@microsoft.graph.conflictBehavior"=> "rename | fail | replace",
    "description"=> "description",
    "fileSystemInfo"=> ["@odata.type"=> "microsoft.graph.fileSystemInfo"]  ,
        "name"=> "ebook.pdf",
      );
        $uploadsession=$graph->createRequest("POST", "/drive/root:/test/ebook.pdf:/createUploadSession")
        ->attachBody($reqBody)
        ->setReturnType(Model\UploadSession::class)
        ->execute();
//2. upload bytes
        $fragSize =320 * 1024;// 1024 * 1024 * 4;
        $fileLocation = 'S:\ebooks\myLargeEbook.pdf';
// check if exists file if not make one
    if (\File::exists($fileLocation)) {
$graph_url = $uploadsession->getUploadUrl();
        $fileSize = filesize($fileLocation);
$numFragments = ceil($fileSize / $fragSize);
        $bytesRemaining = $fileSize;
        $i = 0;
while ($i < $numFragments) {
            $chunkSize = $numBytes = $fragSize;
            $start = $i * $fragSize;
            $end = $i * $fragSize + $chunkSize - 1;
            $offset = $i * $fragSize;
            if ($bytesRemaining < $chunkSize) {
                $chunkSize = $numBytes = $bytesRemaining;
                $end = $fileSize - 1;
            }
            if ($stream = fopen($fileLocation, 'r')) {
                // get contents using offset
                $data = stream_get_contents($stream, $chunkSize, $offset);
                fclose($stream);
            }
$content_range = "bytes " . $start . "-" . $end . "/" . $fileSize;
$headers = array(
                "Content-Length"=> $numBytes,
                "Content-Range"=> $content_range
            );
$uploadByte = $graph->createRequest("PUT", $graph_url)
            ->addHeaders($headers)
            ->attachBody($data)
                ->setReturnType(Model\UploadSession::class)
                ->setTimeout("1000")
                ->execute();
$bytesRemaining = $bytesRemaining - $chunkSize;
            $i++;
        }

    }
    dd($uploadByte);
           }
}

OneDrive File Upload (any size / any location: personal and shared , I tested the code in the /MIchaelMainer/working branch, and it worked fine. question about OneDrive Large File Upload (> 4MB in size) about this issue. So, I don't think this is a limitation of the SDK, but in the API itself. /49822779/​upload-new-file-to-onedrive-using-microsoft-graph-c-sharp-asp-net  The SDK design requirements documentation provides more details about the features and capabilities of the SDK. Request or vote on additional features at the Microsoft Graph UserVoice site. For a list of SDKs and samples for Microsoft Graph, see the Microsoft Graph resources page. Related Articles


<?php
require __DIR__.'/path/to/vendor/autoload.php';

use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;

$graph = new Graph();
$graph->setAccessToken('YOUR_TOKEN_HERE');

/** @var Model\UploadSession $uploadSession */
$uploadSession = $graph->createRequest("POST", "/me/drive/items/root:/doc-test2.docx:/createUploadSession")
    ->addHeaders(["Content-Type" => "application/json"])
    ->attachBody([
        "item" => [
            "@microsoft.graph.conflictBehavior" => "rename",
            "description"    => 'File description here'
        ]
    ])
    ->setReturnType(Model\UploadSession::class)
    ->execute();

$file = __DIR__.'/path/to/large-file.avi';
$handle = fopen($file, 'r');
$fileSize = fileSize($file);
$fileNbByte = $fileSize - 1;
$chunkSize = 1024*1024*4;
$fgetsLength = $chunkSize + 1;
$start = 0;
while (!feof($handle)) {
    $bytes = fread($handle, $fgetsLength);
    $end = $chunkSize + $start;
    if ($end > $fileNbByte) {
        $end = $fileNbByte;
    }
    /* or use stream
    $stream = \GuzzleHttp\Psr7\stream_for($bytes);
    */
    $res = $graph->createRequest("PUT", $uploadSession->getUploadUrl())
        ->addHeaders([
            'Content-Length' => ($end - 1) - $start,
            'Content-Range' => "bytes " . $start . "-" . $end . "/" . $fileSize
        ])
        ->setReturnType(Model\UploadSession::class)
        ->attachBody($bytes)
        ->execute();

    $start = $end + 1;
}

It's work for Me !

Problem uploading larger file · Issue #47 · krizalys/onedrive-php-sdk , When I upload a larger file, I get this: Severity: Error --> Allowed memory which switched to the official Microsoft Graph client to interact with OneDrive. use this API to upload files: https://github.com/krizalys/onedrive-php- If you still have issues with big files in version 2, please kindly reopen this issue. Upload or replace the contents of a DriveItem. 09/10/2017; 2 minutes to read; In this article. The simple upload API allows you to provide the contents of a new file or update the contents of an existing file in a single API call. This method only supports files up to 4MB in size. To upload large files see Upload large files with an upload session.


File Upload Task, Requirements and design documents for Microsoft Graph SDKs. Uploading a large file can be done by creating an upload session which allows the upload of slices of the file in sequential API requests. In the event that a slice fails to upload, the task should retry to re-upload the slice for a configurable number of  The default stream represents the contents of the file. Other streams may be used to represent item thumbnails or alternative data formats. There are four OneDrive APIs that can be used to upload the contents of an item. The correct method to use depends on where the content is coming from and how large the contents of the item are.


Upload a large file into Shared Folder through Microsoft Graph API , Upload a large file into Shared Folder through Microsoft Graph API app only asp.​net In Azure, my app has read/write permissions for files through Microsoft Graph. WriteLine("We could not upload the file: " + e.Error.Message); return null; } } As soon as Net SDK to upload a file to my Dropbox with a valid access token. OneDrive Photo Browser (Windows/C#) An example Universal Windows App that uses the Microsoft Graph SDK to browse images from a user's OneDrive or OneDrive for Business. Data Robot Azure Function An example ASP.NET MVC application and Azure Function to handle webhook notifications and data collaboration in Excel files.


Onedrive Api Download File, This includes documentation for a portion of the Microsoft Graph that accesses Php upload/download of files using Onedrive REST webservice We would like to OneDrive Filepicker SDK can be used to get Files from OneDrive which you could You can quickly upload large files in the background as well as utilize your  Navigate to the Preview App Registrations experience in the Azure AD portal and assign the delegated permission for Files.ReadWrite.All under Microsoft Graph API. Upload a small file. For files less than 4MB you can use a PUT to upload the file directly to the location you want.