Search code examples
c#onedrive

"maximum request length exceeded" When uploading a file to Onedrive


I'm using the sample code from "OneDriveApiBrowser" as the base for adding save to one drive support to my app. This makes use of Microsoft.Graph, I can upload small files but larger files (10Mb) will not upload and give an error "maximum request length exceeded". I get the same error in both my app and the sample code with the following line of code:

DriveItem uploadedItem = await graphClient.Drive.Root.ItemWithPath(drivePath).Content.Request().PutAsync<DriveItem>(newStream);

Is there a way to increase the maximum size of file that can be uploaded? If so how?


Solution

  • Graph will only accept small files using PUT-to-content, so you'll want to look into creating an upload session. Since you're using the Graph SDK I'd use this test case as a guide.

    Here's some code for completeness - it won't directly compile but it should let you see the steps involved:

    var uploadSession = await graphClient.Drive.Root.ItemWithPath("filename.txt").CreateUploadSession().Request().PostAsync();
    
    var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
    
    var provider = new ChunkedUploadProvider(uploadSession, graphClient, inputStream, maxChunkSize);
    
    // Setup the chunk request necessities
    var chunkRequests = provider.GetUploadChunkRequests();
    var readBuffer = new byte[maxChunkSize];
    var trackedExceptions = new List<Exception>();
    
    DriveItem itemResult = null;
    
    //upload the chunks
    foreach (var request in chunkRequests)
    {
        var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);
    
        if (result.UploadSucceeded)
        {
            itemResult = result.ItemResponse;
        }
    }